Four problems about joining everything at the lowest cost. The move: the cheapest link between two groups is always safe, so sort, merge groups with union-find, and turn every extra into a link.
You work on a road planner, a data-centre team and a content network. The four problems on this street join items at the lowest total cost, with no link that is not needed. A set of links like that is a minimum spanning tree.
The Academy lesson Union-find tells you whether two items are already joined. The only new question is which link to try next. Read the table by its third column.
| Problem | The links are given as | The extra twist |
|---|---|---|
| Connect cities with the least cost | a list of roads | stop when exactly the wanted regions remain |
| Cheapest way to connect all depots | every pair of points | some links are already built, and cost nothing |
| Min cost to supply water | a list of links, plus an uplink for each server | a second goal: the fewest uplinks |
| Critical and pseudo critical links | a list of links | classify each link as must-have, optional or unused |
Exercise · Predict the output: Stop at two groups. Roads are sorted by cost, and a road is built when its towns are in different groups. The loop stops when 2 groups remain. What does this print?
roads = [[0, 1, 1], [1, 2, 2], [2, 3, 6], [3, 4, 1], [0, 4, 9], [1, 3, 3]]
parent = [0, 1, 2, 3, 4]
groups, total = 5, 0
for a, b, cost in sorted(roads, key=lambda r: r[2]):
if groups == 2:
break
ra, rb = a, b
while parent[ra] != ra:
ra = parent[ra]
while parent[rb] != rb:
rb = parent[rb]
if ra != rb:
parent[ra] = rb
groups -= 1
total += cost
print(total)One rule drives every problem here, and it needs no search.
The cheapest link between two different groups belongs to some cheapest tree. So build it, merge the two groups, and repeat. A link inside one group would close a loop, so skip it.
The rule gives two algorithms, and the way the links are given picks one.
| The links are | Algorithm | How it works |
|---|---|---|
| a list | Kruskal | sort the links, build each one whose ends are in different groups |
| every pair of points | Prim | grow one tree, and keep the cheapest link from each outside item |
Union-find answers "different groups?" in almost constant time, so Kruskal costs the sort, m log m. Prim needs only one number for each outside item, so for n points it costs n squared steps and builds no list.
Every extra becomes a link of the same graph. A built link costs 0. An uplink from an origin becomes a link to a hidden origin node. A tie between equal costs is a sort order, and you choose it for the second goal.
Take roads cheapest first and build each one that joins two groups. Stop when the wanted number of groups remains.
Exercise · Put it in order: Kruskal's total. Arrange the lines into a function that returns the lowest total cost of roads that join all n towns. Assume the roads connect every town.
def cheapest_total(n, roads):
parent = list(range(n))
total = 0
for a, b, cost in sorted(roads, key=lambda r: r[2]):
ra, rb = find(parent, a), find(parent, b)
if ra != rb:
parent[ra] = rb
total += cost
return total
for a, b, cost in sorted(roads, key=lambda r: -r[2]):
if ra == rb:The Academy lesson Union-find gives the groups and the cycle test. Sort, then choose shows why a sorted greedy rule needs an argument. This street adds the safe-link argument and three things around it.
Links need not be listed. For 1,000 depots on a map, every pair can be linked, which is 499,500 links. For 10,000 depots it is 49,995,000, too many to sort. Prim keeps 1,000 or 10,000 numbers, and never builds the list.
Extras become links. In the supply problem, buying every uplink costs 19 on the first example, and the right plan costs 13. Buying nothing but links costs 9 and leaves the servers cut off from the origin. The hidden origin node makes both choices part of one graph.
Ties are a design choice. Two servers cost 7 each to connect directly, and the link between them also costs 7. Sorting uplinks first returns the plan [14, 2]. Sorting links first returns [14, 1], which has fewer uplinks.
Classifying links costs many runs. With 200 links, the method runs Kruskal 2 x 200 + 1 = 401 times, which is 80,200 union-find steps.
Equal costs need an order. Put links before uplinks, and the plan buys fewer uplinks at the same total.
Exercise · Break it: Roads that run out. This builds the cheapest roads until exactly the wanted number of regions remain, and returns the cost, or -1 when that is impossible. Find an input where it gives the wrong answer.
def cheapest_regions(towns, roads, regions):
parent = list(range(towns))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
groups, total = towns, 0
for a, b, cost in sorted(roads, key=lambda r: r[2]):
if groups == regions:
break
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
groups -= 1
total += cost
return totalSolve them in this order. The first is plain Kruskal, the second uses Prim, the third adds a hidden origin, and the last runs Kruskal many times.
Before you code each problem, write two lines: how the links are given, and what each extra becomes as a link. If every pair can be linked, choose Prim.
Give each problem about 25 minutes. Spend the first four on the two lines, and say them aloud as you would to an interviewer. Then write what the answer is when the items cannot all be joined.
Three edge cases return on every rung. A link may join an item to itself, and union-find skips it. Two links may join the same pair, and the cheaper one wins. An input with one item needs no link and costs 0.
When a solution fails, check the order of the sort before the loop. Most wrong answers on this street come from ties in the wrong order, or from a count of groups that is never checked at the end.
Checkpoint · Minimum spanning trees
Q1/5 Which link is always safe to build when you join groups at the lowest cost?
Answer: B
The cheapest link across a gap belongs to some cheapest tree. A link inside one group would close a loop.
Q2/5 A map has 10,000 depots, and every pair can be linked. Which algorithm avoids sorting 49,995,000 links?
Answer: B
Prim needs one number per outside item and n squared steps, and it never builds the list of links.
Q3/5 Servers can be reached by an uplink from an origin or by links between them. How do you fit the uplinks into Kruskal?
Answer: B
Every uplink becomes a link of the same graph. Then one Kruskal run chooses between links and uplinks.
Q4/5 Two servers cost 7 each by uplink, and the link between them costs 7. Which tie order gives the fewest uplinks?
Answer: B
With links first, the link joins the two servers and only one uplink is bought: the plan is [14, 1]. Uplinks first buys two: [14, 2].
Q5/5 Roads run out while more regions remain than you wanted. What must the answer be?
Answer: C
The loop can end because the roads ran out. Check the number of groups afterwards, and return -1 when it is not the wanted number.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.