Dit boek is nog niet beschikbaar in het Nederlands. Edities: English.
University Computer Science — Year 1 · Bachelor jaar 1
26Minimum Spanning Trees and Union–Find
Brenmoor wants fibre to every place, laid along its roads. Every place must be connected to every other, through the cable if not directly, and cable costs by the metre. The town has 61 kilometres of road; how little of it can carry the fibre? The cheapest network never closes a loop, since removing one road of a loop disconnects nothing: it is a tree, and the question is to find the lightest one. Two greedy algorithms find it, and their proofs rest on one exchange argument. The faster of them needs to answer, again and again, “are these two places already connected?”, and the data structure that answers it in almost constant time is the second subject of the chapter.
You already know
A free tree on vertices is connected with edges (Proposition 24.9). Greedy algorithms are proved by exchange (Chapter 22); binary heaps are in Chapter 18.
26.1 Spanning trees and the cut property
Definition 26.1 (Spanning tree, minimum spanning tree)
A spanning tree of a connected undirected graph is a subgraph that contains every vertex of and is a free tree. In a weighted graph, its weight is the sum of the weights of its edges, and a minimum spanning tree is a spanning tree of smallest weight.
Definition 26.2 (Cut, crossing edge)
A cut of a graph is a partition of its vertices into two non-empty sets and . An edge crosses the cut if it has one end in each set.
Theorem 26.3 (Cut property, cycle property)
Let be a connected weighted graph. (Cut property) For any cut, a lightest edge crossing it belongs to some minimum spanning tree; if it is the only lightest one, to every minimum spanning tree. (Cycle property) An edge strictly heavier than every other edge of some cycle belongs to no minimum spanning tree.
Proof. Let be a lightest edge crossing the cut , , and a minimum spanning tree without . The path from to in starts in and ends outside, so one of its edges, , crosses the cut. Removing from splits it into two trees, one containing and one ; adding joins them again. The result is a spanning tree of weight , so it is minimum and contains . If is the only lightest edge, and would be lighter than : so no minimum spanning tree lacks . For the cycle property, let be the heaviest edge of a cycle , in a spanning tree . Removing splits into two parts, a cut that crosses; the rest of joins the ends of , so it has another edge crossing that cut, and is a lighter spanning tree. ∎
With distinct weights the minimum spanning tree is unique (Exercise 26.10): every edge of it is the only lightest edge across some cut.
26.2 Kruskal’s algorithm
Method 26.4 (Kruskal’s algorithm)
Take the edges by increasing weight; keep an edge if it joins two different trees of the forest kept so far, that is, if it closes no cycle. Stop at edges.
Each kept edge is a lightest edge crossing the cut between the tree of and the rest, since every lighter edge crossing it was examined earlier and would have been kept; by the cut property, it belongs to a minimum spanning tree together with the edges kept before it (the exchange of the proof never removes them, since none of them crosses that cut). By induction, the forest is always contained in some minimum spanning tree, and at edges it is one.
$ python mst_town.py
30 places, 53 roads, 61140 m of road in all
def kruskal(vertices, edges):
"""(tree, uf): tree is the list of edges kept, as (w, u, v)."""
uf, tree = UnionFind(vertices), []
for w, u, v in sorted(edges):
if uf.union(u, v): # u and v were in different trees: no cycle
tree.append((w, u, v))
if len(tree) == len(vertices) - 1:
break
return tree, uf
$ python kruskal.py
29 roads, 27210 m of fibre; 65 parent steps in the finds
shortest three:
Town Hall-River Park 460; Football Ground-Cinema 510; Museum-Lighthouse Café 530
longest: South School-Theatre 1540
figures/mst_map.py: on the left a forest of short roads, scattered over the town; on the right the minimum spanning tree.Sorting costs . The rest is tests “same tree?” and merges; done naively, by searching the forest, each test costs , and Kruskal’s algorithm .
26.3 Disjoint sets
Definition 26.5 (Disjoint-set structure, representative)
A disjoint-set structure, or union–find, keeps a partition of a set of elements, at first into singletons, under two operations: find(x) returns the representative of the set of , the same element for all members of a set; union(x, y) merges the sets of and .
Two naive versions come first. One stores a label per element: find reads it in , union relabels a whole set, . The other stores, for each element, a parent; the representative is the root, reached by climbing: union links one root under the other, and find costs the height of the tree.
def union(self, x, y):
a, b = self.label[x], self.label[y]
for z in self.label: # every element looked at
self.work += 1
if self.label[z] == b:
self.label[z] = a
def find(self, x):
while self.parent[x] != x:
x = self.parent[x]
self.work += 1
return x
def union(self, x, y):
self.parent[self.find(y)] = self.find(x)
$ python uf_naive.py
n = 100: Labels 9900 steps
n = 100: Pointers 9801 steps
n = 1000: Labels 999000 steps
n = 1000: Pointers 998001 steps
Definition 26.6 (Union by rank, path compression)
Each root carries a rank, 0 at the start. Union by rank links the root of smaller rank under the other, and raises the rank of the new root by one when the two ranks were equal. Path compression makes every element met by a find point straight at the root.
class UnionFind:
def __init__(self, items):
self.parent = {x: x for x in items}
self.rank = {x: 0 for x in items}
self.steps = 0 # parent pointers followed by find
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
self.steps += 1
while self.parent[x] != root: # path compression: point straight at the root
self.parent[x], x = root, self.parent[x]
return root
def union(self, x, y):
"""Merge the sets of x and y; False if they were already one set."""
rx, ry = self.find(x), self.find(y)
if rx == ry:
return False
if self.rank[rx] < self.rank[ry]:
rx, ry = ry, rx
self.parent[ry] = rx # the shorter tree goes under the taller
if self.rank[rx] == self.rank[ry]:
self.rank[rx] += 1
return True
Proposition 26.7 (Height under union by rank)
Without path compression, the tree of a root of rank has height and at least elements. So with elements every tree has height at most , and find costs .
Proof. A rank changes only when two trees of equal rank are joined: the new tree has height and at least elements. Joining under a root of larger rank changes neither its rank nor its height, which already exceeds the other’s by one at least. The size bound is Exercise 26.9; then gives . ∎
$ python rank_height.py
n = 16: random unions 2, pairing 4, log2 n = 4
n = 256: random unions 4, pairing 8, log2 n = 8
n = 4096: random unions 5, pairing 12, log2 n = 12
n = 65536: random unions 6, pairing 16, log2 n = 16
c climbs three parent pointers; afterwards c, b and a hang from the root, and the next find from any of them climbs one. Ranks are not updated: a rank remains an upper bound on the height.With both improvements, a sequence of operations on elements costs , where is an inverse of Ackermann’s function of Proposition 11.14: it grows so slowly that for any that can be written down. Tarjan proved this bound in 1975; its proof is beyond this book, and we admit it.
$ python union_find.py
n = 100: 197 steps, largest rank 1
n = 1000: 1997 steps, largest rank 1
n = 10000: 19997 steps, largest rank 1
Kruskal’s algorithm now costs for the sort and for the rest: on the town, 65 parent steps in all for the 53 roads.
26.4 Prim’s algorithm
Method 26.8 (Prim’s algorithm)
Grow a single tree from a start vertex: repeatedly add the lightest edge with exactly one end in the tree, and its other end.
Each added edge is a lightest edge across the cut between the tree and the rest, so the cut property proves the algorithm, as for Kruskal’s. A heap holds the edges leaving the tree; an edge whose two ends have entered the tree is discarded when it comes off the heap, as with lazy deletion in Dijkstra’s algorithm.
def prim(vertices, edges, start):
adj = {v: [] for v in vertices}
for w, u, v in edges:
adj[u].append((w, v))
adj[v].append((w, u))
inside, tree, pops = {start}, [], 0
heap = [(w, start, v) for w, v in adj[start]]
heapq.heapify(heap)
while heap and len(inside) < len(vertices):
w, u, v = heapq.heappop(heap)
pops += 1
if v in inside: # both ends inside: the edge no longer crosses the cut
continue
inside.add(v)
tree.append((w, u, v))
for x in adj[v]:
if x[1] not in inside:
heapq.heappush(heap, (x[0], v, x[1]))
return tree, pops
$ python prim.py
from 1: 29 roads, 27210 m, 44 pops
from 8: 29 roads, 27210 m, 44 pops
Each edge enters the heap at most once, when the first of its ends enters the tree (the other end is then still outside): . Prim’s algorithm suits dense graphs, given as a matrix: with an array of best edges instead of a heap it costs , with no sort of the edges. Kruskal’s suits sparse graphs and edges that arrive as a list. Kruskal published his algorithm in 1956, and Prim his in 1957, for networks of telephone lines.
26.5 Bottlenecks
Definition 26.9 (Bottleneck spanning tree)
A bottleneck spanning tree is a spanning tree whose heaviest edge is as light as possible among all spanning trees.
A minimum spanning tree is a bottleneck spanning tree (Exercise 26.11). More: for any two vertices, the path joining them in a minimum spanning tree minimises the heaviest edge among all paths between them. Read with maxima, a maximum spanning tree gives the widest paths, those whose narrowest edge is widest, for every pair at once. Removing the heaviest edges of a minimum spanning tree splits the vertices into clusters, which maximise the smallest distance between two clusters; the next volume uses this for clustering data.
26.6 Exercises
Exercise 26.1 ★
A graph on has the edges 4, 1, 3, 2, 5, 7, 6. Give the edges kept by Kruskal’s algorithm, in order, and the weight.
Solution
Solution of Exercise 26.1.
By increasing weight: (1) kept, (2) kept, (3) kept, joining and ; (4) and (5) close cycles; (6) kept. The tree weighs 12.
Exercise 26.2 ★
Run Prim’s algorithm from on the same graph: in which order do the vertices enter?
Solution
Solution of Exercise 26.2.
From : (6) brings ; then (2) brings ; then (3) brings ; then (1) brings . The order is , and the tree is the same, of weight 12.
Exercise 26.3 ★
Starting from six singletons , run union(0, 1), union(2, 3), union(1, 3), union(4, 5), union(5, 0) with Listing 26.3. Give the parents and ranks at the end.
Solution
Solution of Exercise 26.3.
union(0, 1): 1 under 0, rank of 0 becomes 1. union(2, 3): 3 under 2, rank of 2 becomes 1. union(1, 3): the roots 0 and 2 both have rank 1, so 2 goes under 0, whose rank becomes 2. union(4, 5): 5 under 4, rank 1. union(5, 0): the root 4 has rank 1, the root 0 rank 2, so 4 goes under 0. Parents: , , , , , ; ranks 2 for 0, 1 for 2 and 4, 0 for the others.
Exercise 26.4 ★
In the graph of Exercise 26.1, is the tree a minimum spanning tree? Use the cycle property.
Solution
Solution of Exercise 26.4.
Yes. Each edge outside the tree is the heaviest of a cycle: (4) of ; (5) of ; (7) of . By the cycle property none of them is in a minimum spanning tree, and the four edges left are exactly the given tree.
Exercise 26.5 ★★
This version replaces union–find by a set of visited places. Why does it keep only 21 roads?
def kruskal_visited(vertices, edges):
visited, tree = set(), []
for w, u, v in sorted(edges):
if u not in visited or v not in visited: # "no cycle if an end is new"
visited |= {u, v}
tree.append((w, u, v))
return tree
21 roads kept for 30 places
Solution
Solution of Exercise 26.5.
An edge whose two ends are both visited is rejected, even when they lie in different trees of the forest: two groups of places that grew apart are never joined. The edges kept close no cycle, since one end is always new, so they form a forest; 21 edges on 30 places leave trees. Testing “same tree?” needs union–find, not a flag.
Exercise 26.6 ★★
Find the error in this union by rank, and explain the tree of height 999.
def union(self, x, y):
rx, ry = self.find(x), self.find(y)
if rx == ry:
return False
if self.rank[rx] < self.rank[ry]:
rx, ry = ry, rx
self.parent[ry] = rx
if self.rank[rx] == self.rank[ry]:
self.rank[ry] += 1
return True
UnionFind tallest tree 1, root rank 1
Buggy tallest tree 999, root rank 0
union(i, i - 1) for from 1 to 999, before any other find. Some lines are left out.Solution
Solution of Exercise 26.6.
On equal ranks it raises the rank of ry, the root that has just become a child, instead of the new root rx. Roots keep rank 0, so every union is between equal ranks and links the root of y under the root of x. In union(i, i - 1), i is a fresh singleton: the whole chain goes under it, one level deeper each time, and the finds of i and i - 1, at the top, compress nothing. After 999 unions the chain has height 999.
Exercise 26.7 ★★
Compute the weight of a second-best spanning tree, the lightest spanning tree different from the minimum one, by swapping one edge of the minimum spanning tree for one outside it; test it against all spanning trees of small graphs.
Solution
Solution of Exercise 26.7.
def second_best(vertices, edges):
tree, _ = kruskal(vertices, edges)
others = [e for e in edges if e not in tree]
best = None
for out in tree:
for e in others:
candidate = [t for t in tree if t != out] + [e]
uf = UnionFind(vertices)
if all(uf.union(u, v) for _, u, v in candidate): # still a spanning tree
w = sum(x[0] for x in candidate)
best = w if best is None else min(best, w)
return best
It is a known fact, which the test checks on small graphs with distinct weights, that some second-best tree differs from the minimum spanning tree by a single exchange. The program tries the exchanges and checks each candidate with union–find: , enough for small graphs. The test compares with the second smallest weight among all spanning trees.
Exercise 26.8 ★★
Generate a maze on a grid of cells by Kruskal’s algorithm on the walls taken in a random order, seeded. Why is every cell reachable from every other, by exactly one way?
Solution
Solution of Exercise 26.8.
def maze(rows, cols, seed):
rng = random.Random(seed)
cells = [(r, c) for r in range(rows) for c in range(cols)]
walls = [((r, c), (r, c + 1)) for r in range(rows) for c in range(cols - 1)]
walls += [((r, c), (r + 1, c)) for r in range(rows - 1) for c in range(cols)]
rng.shuffle(walls) # random order = random distinct weights
uf, opened = UnionFind(cells), []
for a, b in walls:
if uf.union(a, b):
opened.append((a, b))
return opened
The cells and the walls between neighbours form a connected grid graph; a random order of the walls is a random order of distinct weights, and Kruskal’s algorithm opens the walls of a spanning tree. Connected: every cell is reachable; no cycle: by exactly one way. The seed makes the maze the same at every run.
Exercise 26.9 ★★
Show that with union by rank a root of rank has at least elements in its tree, with or without path compression.
Solution
Solution of Exercise 26.9.
By induction over the operations. At the start every root has rank 0 and 1 element. A root’s rank goes from to only when another root of rank is put under it; each had at least elements, so the merged tree has at least . Linking under a root of larger rank only adds elements. Path compression changes parents inside a tree, never which elements a root’s tree holds, nor any rank.
Exercise 26.10 ★★★
Show that a connected graph whose edge weights are all distinct has exactly one minimum spanning tree.
Solution
Solution of Exercise 26.10.
Suppose are minimum spanning trees, and let be the lightest edge in one but not the other, say in . Adding to closes a cycle, which has an edge not in , since has no cycle. Then is in but not , so , the weights being distinct and the lightest such edge. is a spanning tree lighter than : a contradiction.
Exercise 26.11 ★★★
Show that every minimum spanning tree is a bottleneck spanning tree, and give a bottleneck spanning tree that is not minimum.
Solution
Solution of Exercise 26.11.
Let be a minimum spanning tree with heaviest edge , and any spanning tree. Removing splits into two parts, a cut; is connected, so it has an edge across that cut. If , would be a lighter spanning tree; so , and the heaviest edge of weighs at least . For the converse, take a triangle with of weight 1 and , of weight 2: the tree has heaviest edge 2, as small as possible, but weighs 4 against 3.
Exercise 26.12 ★★★
Borůvka’s method works in rounds: each tree of the forest, at first the single vertices, picks its lightest leaving edge, and all picked edges are added. Implement it with union–find, prove that it needs at most rounds, and test it against Kruskal’s algorithm.
Solution
Solution of Exercise 26.12.
def boruvka(vertices, edges):
"""Distinct weights, or ties broken consistently, as by comparing the tuples."""
uf, tree, rounds = UnionFind(vertices), [], 0
while len(tree) < len(vertices) - 1:
rounds += 1
cheapest = {}
for e in edges:
ru, rv = uf.find(e[1]), uf.find(e[2])
if ru != rv:
for r in (ru, rv):
if r not in cheapest or e < cheapest[r]:
cheapest[r] = e
if not cheapest:
break # the graph is not connected
for e in set(cheapest.values()):
if uf.union(e[1], e[2]):
tree.append(e)
return tree, rounds
With weights made distinct by comparing the tuples, each picked edge is the only lightest edge leaving its tree, so it is in the minimum spanning tree by the cut property, and the picked edges close no cycle. Each tree is merged with at least one other in a round, so the number of trees at least halves: at most rounds, each . On Brenmoor it takes 3 rounds and finds 27 210 m; the test compares it with Kruskal’s algorithm on random graphs.
26.7 Problem: Laying fibre in Brenmoor
Problem 26.1
Weekend problem — Laying fibre in Brenmoor
The council has chosen to lay fibre along a minimum spanning tree of the roads, weighted by length. Before trusting the algorithms with the whole town, it counts the trees of a small piece of it.
def spanning_trees(vertices, edges):
"""Every set of n - 1 edges without a cycle: exactly the spanning trees."""
for chosen in combinations(edges, len(vertices) - 1):
uf = UnionFind(vertices)
if all(uf.union(u, v) for _, u, v in chosen):
yield chosen
$ python count_trees.py
9 places, 11 roads: 37 spanning trees among 165 sets of 8 roads
lightest by brute force 10130 m, by Kruskal 10130 m
$ python bottleneck.py
from Town Square: tree answers = direct search for all 30 places: True
to the Hospital: no route avoids a road of 1240 m
2 clusters: sizes [29, 1]
3 clusters: sizes [26, 3, 1]
4 clusters: sizes [26, 2, 1, 1]
5 clusters: sizes [24, 2, 2, 1, 1]
Part I — Spanning trees of a piece of the town.
- Why does a set of edges without a cycle form a spanning tree?
- Why are only 37 of the 165 sets of 8 roads spanning trees?
- How many sets would the brute force try for the whole town, ? Estimate its order of magnitude.
- Why does
allstop at the first union that fails, and why is that correct? - The lightest tree found by brute force weighs the same as Kruskal’s: what does that check, and what not?
- How many cycles at least does the piece have, given 9 places and 11 roads?
Part II — The whole town.
- Read the fibre length and the number of roads used.
- Why do Kruskal’s and Prim’s algorithms give the same weight from any start?
- Are the road lengths distinct? If not, could two minimum spanning trees exist?
- Count the heap pops of Prim’s algorithm, and explain the 44.
- Which of the two algorithms would you use for a town of a million places and three million roads?
- Why is the longest road of the tree, 1540 m, kept although longer roads exist?
Part III — Union–find.
- Explain the 9900 and 9801 steps of Output 26.3.
- Why does the chain cost about steps with union by rank and path compression?
- Why does the largest rank stay at 1 on this chain?
- Why do random unions give trees much lower than ?
- Describe the unions that reach height exactly.
- Why does
findnot update ranks when it compresses?
Part IV — Bottlenecks.
- Prove that for two vertices and , the path from to in a minimum spanning tree has the smallest possible heaviest edge among all paths from to .
- What does “no route avoids a road of 1240 m” mean for a lorry that must avoid long roads?
- How was the bottleneck computed without the tree, and why do the two answers agree?
- Explain the clusters of sizes 29 and 1, then 26, 3 and 1.
- Is removing the longest tree roads a good way to split the town into districts?
- State the named result, the minimum fibre length of Brenmoor, with the bottleneck theorem.
Solution
Solution of Problem 26.1.
1. Each edge that closes no cycle joins two components, so of them leave component: the graph is connected and acyclic, a free tree on all the vertices.
2. The 128 others contain a cycle; with 8 edges on 9 places, a set with a cycle leaves some place out.
3. sets, each checked with union–find: years of computing.
4. all stops at the first False: a failed union means that the edge closes a cycle, and the set is not a tree whatever the other edges.
5. That Kruskal’s algorithm found an optimal tree on this piece; not that it does on every graph, which is the proof’s job.
6. A connected graph has at least independent cycles: here , so at least three cycles.
7. 27 210 m, along 29 roads.
8. Both compute minimum spanning trees, and all minimum spanning trees have the smallest weight, by definition.
9. No: 53 roads have 47 distinct lengths. Two minimum spanning trees may then exist, of the same weight; the program prints one.
10. 29 pops add a place; the other 15 take off edges whose two ends were already in the tree. Each road is pushed at most once, when its first end enters the tree: prim.py pushes an edge only if its other end is still outside.
11. Either: Kruskal’s with union–find costs for the sort, and Prim’s with a heap ; the graph is sparse, so Prim’s array version would be the wrong one.
12. It is the lightest road across the cut that separates the South School from the rest: the school’s other roads are longer still, and the longer roads elsewhere close cycles.
13. Labels: each of the 99 unions scans the 100 elements, 9900 steps. Pointers: after unions the chain has height ; the -th union climbs steps in find(0) and the following find steps: .
14. Each fresh element goes under the root, and 0 hangs from the root after the first compression: each union and each find climbs at most one pointer, in all.
15. The root reaches rank 1 at the first union; every later union links a singleton of rank 0 under it.
16. Random unions mostly link a small tree under a large one, which does not raise the height; trees of equal large rank rarely meet.
17. Merge the singletons in pairs, then the pairs in pairs, and so on: always two trees of equal rank, whose height grows by one at each level, levels in all.
18. Computing the new heights would cost more than the find; ranks stay upper bounds on heights, which is all the proof of the logarithmic bound needs.
19. Let be the heaviest edge on the path from to in a minimum spanning tree . Removing splits into two parts, on one side and on the other. Any path from to crosses this cut at some edge , and , or would be a lighter spanning tree. So every path has an edge at least as heavy as .
20. Every route from the Town Square to the Hospital uses a road of at least 1240 m, and the route through the tree uses none longer.
21. By Dijkstra’s algorithm with in place of , which is correct for the same reason as the widest-path variant of Exercise 25.8; the two answers agree by question 19.
22. The longest tree road leads to the South School, a leaf of the tree: removing it isolates one place. The next one, Post Office–College, cuts off three places.
23. Not by itself: removing the longest roads peels off outlying places one by one rather than splitting the town into balanced districts. It is the right method when clusters are separated by gaps, which a town’s roads are not.
24. The minimum fibre length of Brenmoor is 27 210 m, computed by Kruskal’s and Prim’s algorithms alike. By the bottleneck theorem (question 19 and Exercise 26.11), its longest road, 1540 m, is the smallest possible longest road of any network joining all the places, and the tree’s paths are minimax routes.