progress

~/problems / Weighted graphs / Minimum spanning tree

Finish the irrigation network

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

A farm has fields 0 .. n-1. Pipes (a, b) in existing are already laid (free, two-way). New pipes can be laid from the quote list options of (a, b, cost).

Implement extra_cost(n, existing, options) -> int | None: the minimum cost of new pipes so every field connects to every other, or None if even all the options aren't enough.

existing = [(0, 1), (2, 3)]
options = [(1, 2, 7), (0, 3, 4), (3, 4, 2), (0, 4, 9), (1, 3, 5)]
extra_cost(5, existing, options)   # 6   lay (3, 4) for 2 and (0, 3) for 4
Five fields with pipes 0-1 and 2-3 already laid and five quoted pipes dashed with their costs; laying 3-4 for 2 and 0-3 for 4 connects every field for 6.
extra_cost(3, [], [(0, 1, 1)])     # None: field 2 can't be reached
extra_cost(2, [(0, 1)], [(0, 1, 3)])   # 0: already connected

Up to 10^5 fields, 10^5 existing pipes and 2 * 10^5 options; pairs may repeat.

⭐ Bonus: a speed test with 100,000 fields earns a star in O(m log m): sort once and use union-find.

Show hint

Kruskal: union every existing pipe first, then walk the options by increasing cost, paying for one only when it joins two different groups.

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

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