Informatica · Boek 3 · Bachelor jaar 1

University Computer Science — Year 1

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 nn vertices is connected with n−1n - 1 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 GG is a subgraph that contains every vertex of GG 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 SS and V∖SV \setminus S. An edge crosses the cut if it has one end in each set.

Theorem 26.3 (Cut property, cycle property)

Let GG 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 e=uve = uv be a lightest edge crossing the cut (S,V∖S)(S, V \setminus S), u∈Su \in S, and TT a minimum spanning tree without ee. The path from uu to vv in TT starts in SS and ends outside, so one of its edges, ff, crosses the cut. Removing ff from TT splits it into two trees, one containing uu and one vv; adding ee joins them again. The result T′=T−f+eT' = T - f + e is a spanning tree of weight w(T)−w(f)+w(e)≤w(T)w(T) - w(f) + w(e) \leq w(T), so it is minimum and contains ee. If ee is the only lightest edge, w(e)<w(f)w(e) < w(f) and T′T' would be lighter than TT: so no minimum spanning tree lacks ee. For the cycle property, let ee be the heaviest edge of a cycle CC, in a spanning tree TT. Removing ee splits TT into two parts, a cut that ee crosses; the rest of CC joins the ends of ee, so it has another edge ff crossing that cut, and T−e+fT - e + f is a lighter spanning tree. ∎

The exchange in the cut property: the tree T (thick) joins u to v by a path that crosses the cut at some edge f; swapping f for the lightest crossing edge e keeps a spanning tree and cannot add weight.
The exchange in the cut property: the tree TT (thick) joins uu to vv by a path that crosses the cut at some edge ff; swapping ff for the lightest crossing edge ee keeps a spanning tree and cannot add weight.

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 n−1n - 1 edges.

Each kept edge uvuv is a lightest edge crossing the cut between the tree of uu 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 n−1n - 1 edges it is one.

$ python mst_town.py
30 places, 53 roads, 61140 m of road in all
Output 26.1. The town as an undirected graph: fibre carries data both ways, so the one-way road is an edge like the others.
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
Listing 26.1. Kruskal’s algorithm, with union–find for the cycle test code/bachelor-1/26-spanning-trees/listings/kruskal.py
$ 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
Output 26.2. The fibre network of Brenmoor: 27.2 km of the 61 km of road.
Kruskal’s algorithm on Brenmoor, drawn from the data by figures/mst_map.py: on the left a forest of short roads, scattered over the town; on the right the minimum spanning tree.
Kruskal’s algorithm on Brenmoor, drawn from the data by 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 O(mlog⁡m)=O(mlog⁡n)O(m \log m) = O(m \log n). The rest is mm tests “same tree?” and n−1n - 1 merges; done naively, by searching the forest, each test costs O(n)O(n), and Kruskal’s algorithm O(mn)O(mn).

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 xx, the same element for all members of a set; union(x, y) merges the sets of xx and yy.

Two naive versions come first. One stores a label per element: find reads it in O(1)O(1), union relabels a whole set, O(n)O(n). 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)
Listing 26.2. The union of labels and the find of parent pointers code/bachelor-1/26-spanning-trees/listings/uf_naive.py
$ python uf_naive.py
n =  100: Labels      9900 steps
n =  100: Pointers    9801 steps
n = 1000: Labels    999000 steps
n = 1000: Pointers  998001 steps
Output 26.3. A chain of n−1n - 1 unions each followed by a find: both versions are quadratic.

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
Listing 26.3. Union by rank and path compression, with the parent steps counted code/bachelor-1/26-spanning-trees/listings/union_find.py

Proposition 26.7 (Height under union by rank)

Without path compression, the tree of a root of rank rr has height rr and at least 2r2^r elements. So with nn elements every tree has height at most log⁡2n\log_2 n, and find costs O(log⁡n)O(\log n).

Proof. A rank changes only when two trees of equal rank rr are joined: the new tree has height r+1r + 1 and at least 2r+2r2^r + 2^r 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 2r≤n2^r \leq n gives r≤log⁡2nr \leq \log_2 n. ∎

$ 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
Output 26.4. The tallest tree after random unions, and after merging trees of equal rank two by two: the bound log⁡2n\log_2 n is reached.
Path compression. The find from 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.
Path compression. The find from 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 mm operations on nn elements costs O(m α(n))O(m\, \alpha(n)), where α\alpha is an inverse of Ackermann’s function of Proposition 11.14: it grows so slowly that α(n)≤4\alpha(n) \leq 4 for any nn 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
Output 26.5. The chain of Output 26.3 with both improvements: the work grows linearly.

Kruskal’s algorithm now costs O(mlog⁡n)O(m \log n) for the sort and O(m α(n))O(m\, \alpha(n)) 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
Listing 26.4. Prim’s algorithm with a heap of edges code/bachelor-1/26-spanning-trees/listings/prim.py
$ python prim.py
from 1: 29 roads, 27210 m, 44 pops
from 8: 29 roads, 27210 m, 44 pops
Output 26.6. From two different places, the same weight as Kruskal’s.

Each edge enters the heap at most once, when the first of its ends enters the tree (the other end is then still outside): O(mlog⁡n)O(m \log n). Prim’s algorithm suits dense graphs, given as a matrix: with an array of best edges instead of a heap it costs O(n2)O(n^2), with no sort of the m≈n2/2m \approx n^2 / 2 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 k−1k - 1 heaviest edges of a minimum spanning tree splits the vertices into kk 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 a,b,c,d,ea, b, c, d, e has the edges abab 4, acac 1, bcbc 3, bdbd 2, cdcd 5, cece 7, dede 6. Give the edges kept by Kruskal’s algorithm, in order, and the weight.

Solution

Solution of Exercise 26.1.

By increasing weight: acac (1) kept, bdbd (2) kept, bcbc (3) kept, joining {a,c}\{a, c\} and {b,d}\{b, d\}; abab (4) and cdcd (5) close cycles; dede (6) kept. The tree ac,bd,bc,deac, bd, bc, de weighs 12.

Exercise 26.2 ★

Run Prim’s algorithm from ee on the same graph: in which order do the vertices enter?

Solution

Solution of Exercise 26.2.

From ee: dede (6) brings dd; then bdbd (2) brings bb; then bcbc (3) brings cc; then acac (1) brings aa. The order is e,d,b,c,ae, d, b, c, a, and the tree is the same, of weight 12.

Exercise 26.3 ★

Starting from six singletons 0,…,50, \dots, 5, 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: 0→00 \to 0, 1→01 \to 0, 2→02 \to 0, 3→23 \to 2, 4→04 \to 0, 5→45 \to 4; 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 ac,bc,bd,deac, bc, bd, de 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: abab (4) of a,b,ca, b, c; cdcd (5) of c,d,bc, d, b; cece (7) of c,e,d,bc, e, d, b. 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
Listing 26.5. Kruskal with a visited flag code/bachelor-1/26-spanning-trees/listings/exo_visited.py
21 roads kept for 30 places
Output 26.7. On the town. Some lines are left out.
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 30−21=930 - 21 = 9 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
Listing 26.6. A wrong rank code/bachelor-1/26-spanning-trees/listings/exo_rank_bug.py
UnionFind tallest tree   1, root rank 1
Buggy     tallest tree 999, root rank 0
Output 26.8. The unions union(i, i - 1) for ii 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
A second-best spanning tree code/bachelor-1/26-spanning-trees/exercises/second_best.py

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 (n−1)(m−n+1)(n - 1)(m - n + 1) exchanges and checks each candidate with union–find: O(nm⋅n α(n))O(n m \cdot n\, \alpha(n)), 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
A maze by random Kruskal code/bachelor-1/26-spanning-trees/exercises/maze.py

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 rr has at least 2r2^r 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 rr to r+1r + 1 only when another root of rank rr is put under it; each had at least 2r2^r elements, so the merged tree has at least 2r+12^{r+1}. 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 T1≠T2T_1 \neq T_2 are minimum spanning trees, and let ee be the lightest edge in one but not the other, say in T1T_1. Adding ee to T2T_2 closes a cycle, which has an edge ff not in T1T_1, since T1T_1 has no cycle. Then ff is in T2T_2 but not T1T_1, so w(f)>w(e)w(f) > w(e), the weights being distinct and ee the lightest such edge. T2+e−fT_2 + e - f is a spanning tree lighter than T2T_2: 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 TT be a minimum spanning tree with heaviest edge ee, and BB any spanning tree. Removing ee splits TT into two parts, a cut; BB is connected, so it has an edge ff across that cut. If w(f)<w(e)w(f) < w(e), T−e+fT - e + f would be a lighter spanning tree; so w(f)≥w(e)w(f) \geq w(e), and the heaviest edge of BB weighs at least w(e)w(e). For the converse, take a triangle with abab of weight 1 and bcbc, caca of weight 2: the tree bc,cabc, ca 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 log⁡2n\log_2 n 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
Borůvka’s method code/bachelor-1/26-spanning-trees/exercises/boruvka.py

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 log⁡2n\log_2 n rounds, each O(m α(n))O(m\, \alpha(n)). 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
Listing 26.7. Every spanning tree, by brute force code/bachelor-1/26-spanning-trees/listings/count_trees.py
$ 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
Output 26.9. The places within two roads of the Town Square.
$ 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]
Output 26.10. Minimax routes read from the tree, and clusters obtained by removing its longest roads.

Part I — Spanning trees of a piece of the town.

  1. Why does a set of n−1n - 1 edges without a cycle form a spanning tree?
  2. Why are only 37 of the 165 sets of 8 roads spanning trees?
  3. How many sets would the brute force try for the whole town, (5329)\binom{53}{29}? Estimate its order of magnitude.
  4. Why does all stop at the first union that fails, and why is that correct?
  5. The lightest tree found by brute force weighs the same as Kruskal’s: what does that check, and what not?
  6. How many cycles at least does the piece have, given 9 places and 11 roads?

Part II — The whole town.

  1. Read the fibre length and the number of roads used.
  2. Why do Kruskal’s and Prim’s algorithms give the same weight from any start?
  3. Are the road lengths distinct? If not, could two minimum spanning trees exist?
  4. Count the heap pops of Prim’s algorithm, and explain the 44.
  5. Which of the two algorithms would you use for a town of a million places and three million roads?
  6. Why is the longest road of the tree, 1540 m, kept although longer roads exist?

Part III — Union–find.

  1. Explain the 9900 and 9801 steps of Output 26.3.
  2. Why does the chain cost about 2n2n steps with union by rank and path compression?
  3. Why does the largest rank stay at 1 on this chain?
  4. Why do random unions give trees much lower than log⁡2n\log_2 n?
  5. Describe the unions that reach height log⁡2n\log_2 n exactly.
  6. Why does find not update ranks when it compresses?

Part IV — Bottlenecks.

  1. Prove that for two vertices aa and bb, the path from aa to bb in a minimum spanning tree has the smallest possible heaviest edge among all paths from aa to bb.
  2. What does “no route avoids a road of 1240 m” mean for a lorry that must avoid long roads?
  3. How was the bottleneck computed without the tree, and why do the two answers agree?
  4. Explain the clusters of sizes 29 and 1, then 26, 3 and 1.
  5. Is removing the longest tree roads a good way to split the town into districts?
  6. 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 n−1n - 1 of them leave n−(n−1)=1n - (n - 1) = 1 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. (5329)≈7.8×1014\binom{53}{29} \approx 7.8 \times 10^{14} 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 m−n+1m - n + 1 independent cycles: here 11−9+1=311 - 9 + 1 = 3, 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 O(mlog⁡n)O(m \log n) for the sort, and Prim’s with a heap O(mlog⁡n)O(m \log n); the graph is sparse, so Prim’s O(n2)O(n^2) 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 ii unions the chain has height ii; the ii-th union climbs i−1i - 1 steps in find(0) and the following find ii steps: ∑i=199(2i−1)=992=9801\sum_{i=1}^{99} (2i - 1) = 99^2 = 9801.

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, 2(n−2)+12(n - 2) + 1 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, log⁡2n\log_2 n 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 ee be the heaviest edge on the path from aa to bb in a minimum spanning tree TT. Removing ee splits TT into two parts, aa on one side and bb on the other. Any path from aa to bb crosses this cut at some edge ff, and w(f)≥w(e)w(f) \geq w(e), or T−e+fT - e + f would be a lighter spanning tree. So every path has an edge at least as heavy as ee.

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 max⁡\max 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.

Begrippen gedefinieerd in dit hoofdstuk

Bekijk alle 1050 begrippen in de begrippenlijst