progress

~/problems / Weighted graphs / Minimum spanning tree

Cheapest repairs to reconnect every city

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

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)
Four cities joined by five broken roads; repairing the roads costing 1 (2-3), 2 (1-3) and 7 (3-4) connects every city for 10, and the roads costing 4 and 9 stay broken.
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.

Topic: Minimum spanning tree. Kruskal (sort edges + Union-Find) or Prim (heap).

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc