Cities 1..n are joined by broken two-way roads (a, b, cost). Repair roads so every city can reach every other, spending as little as possible.
Implement road_reparation(n: int, roads: list[tuple[int, int, int]]) -> int | None: the minimum total cost, or None if the cities can't all be connected.
road_reparation(4, [(1, 2, 4), (2, 3, 1), (1, 3, 2), (3, 4, 7), (2, 4, 9)]) # 10 (2 + 1 + 7)
road_reparation(3, [(1, 2, 5)]) # None (city 3 is cut off)
road_reparation(1, []) # 0
Up to 10^5 cities and 2 * 10^5 roads, costs up to 10^9. Roads may repeat a pair or loop back to the same city.
⭐ Bonus: a speed test with 50,000 cities earns a star in O(m log m) for m roads.
Show hint
take roads from cheapest to most expensive and repair one only if it joins two cities not yet connected. A structure that tracks connected groups makes each check fast.