Prim's algorithm builds a minimum spanning tree by repeating one step: take the cheapest edge that leaves the tree so far.
Write cheapest_exit(inside: list[int], edges: list[tuple[int, int, int]]) -> tuple[int, int, int] | None. inside lists the nodes in the group; each edge (a, b, w) joins a and b with weight w. Return the cheapest edge with exactly one end inside the group, as it appears in edges. On a tie, return the one listed first. If no edge leaves the group, return None.
edges = [(0, 1, 4), (0, 2, 1), (1, 2, 2), (2, 3, 5)]
cheapest_exit([0, 2], edges) # (1, 2, 2) (0, 2, 1) is now inside the group
edges = [(0, 1, 4), (0, 2, 1), (1, 2, 2), (2, 3, 5)]
cheapest_exit([0], edges) # (0, 2, 1)
cheapest_exit([0, 1, 2, 3], edges) # None
Constraints: up to 10^4 nodes and edges; weights are in [-10^6, 10^6].
Show hint
put inside in a set. An edge leaves the group when (a in group) != (b in group).