The Generic Method, Cuts and Light Edges
A company wants to connect seven offices with leased lines so that every office can reach every other, and each possible line has a monthly price. The cheapest network contains no cycle, since dropping one edge of a cycle keeps everything connected and saves money. So the answer is a spanning tree, a tree that contains every vertex, of minimum total weight: a minimum spanning tree (MST). The same problem appears in circuit wiring, clustering, and as a building block of approximation algorithms for the travelling salesman problem. The DSA course introduces MSTs by example. This lesson proves the one fact that both classic algorithms, Kruskal's and Prim's, are built on.
The problem
Given a connected undirected graph with weights , find an acyclic subset that connects all vertices and minimizes
A spanning tree always has exactly edges. There can be exponentially many: the program enumerates every subset of edges of a seven-vertex graph, keeps those that form a spanning tree, and finds the cheapest.
from itertools import combinations
edges = [("A", "B", 7), ("A", "D", 4), ("B", "C", 8), ("B", "D", 9), ("B", "E", 3), ("C", "E", 6),
("C", "F", 10), ("D", "E", 11), ("D", "G", 5), ("E", "F", 2), ("E", "G", 12), ("F", "G", 1)]
V = "ABCDEFG"
def is_spanning_tree(subset):
parent = {v: v for v in V}
def find(x):
while parent[x] != x:
x = parent[x]
return x
for u, v, _ in subset:
ru, rv = find(u), find(v)
if ru == rv:
return False # this edge closes a cycle
parent[ru] = rv
return True # V - 1 edges and no cycle: a spanning tree
trees = [t for t in combinations(edges, len(V) - 1) if is_spanning_tree(t)]
weights = sorted(sum(w for _, _, w in t) for t in trees)
best = min(trees, key=lambda t: sum(w for _, _, w in t))
print(f"{len(trees)} spanning trees among {len(list(combinations(edges, 6)))} subsets of 6 edges")
print("lightest weights:", weights[:5], " heaviest:", weights[-1])
print("an MST:", ", ".join(f"{u}{v}:{w}" for u, v, w in best))308 spanning trees among 924 subsets of 6 edges
lightest weights: [21, 23, 23, 24, 25] heaviest: 57
an MST: AD:4, BE:3, CE:6, DG:5, EF:2, FG:1
Enumeration is hopeless beyond toy sizes: a complete graph on vertices has spanning trees (Cayley's formula). The greedy algorithms below find an MST in time instead.
The generic method
Both algorithms grow a set of edges and keep one invariant:
Invariant: is a subset of some minimum spanning tree.
An edge is safe for if is still a subset of some MST.
GENERIC-MST(G, w)
1 A = empty set
2 while A does not form a spanning tree
3 find an edge (u, v) that is safe for A
4 A = A + {(u, v)}
5 return AThe empty set satisfies the invariant, adding a safe edge keeps it, and when the loop ends is a spanning tree contained in an MST, so it is an MST. Everything hinges on line 3: how do we recognise a safe edge?
Cuts and light edges
A cut is a partition of the vertices into two non-empty sides. An edge crosses the cut if one endpoint is in and the other is not. A cut respects a set of edges if no edge of crosses it. An edge is a light edge crossing the cut if its weight is the minimum among all edges crossing the cut (there can be ties).
Theorem (cut property). Let be a subset of some MST , let be any cut that respects , and let be a light edge crossing it. Then is safe for .
Proof
If there is nothing to prove. Otherwise adding to creates exactly one cycle: the edge plus the path from to in . Since and are on opposite sides of the cut, crosses the cut at least once, say at edge . That edge is not in , because the cut respects . Remove it and add :
is a spanning tree: removing splits into two pieces, one containing and one containing , and joins them again. Because is light and also crosses the cut, , so . is minimum, so is minimum too. Finally (we removed only ) and , so .
Corollary. Let be a subset of some MST, and let be one of the connected components (trees) of the forest . A light edge connecting to a vertex outside is safe for . (Use the cut , which respects .)
The two algorithms are the two natural ways to pick the cut. Prim grows a single tree and always cuts it off from the rest. Kruskal takes the globally lightest edge joining two different trees, which is light for the cut around either tree.
Any respecting cut works
The theorem allows any cut that respects , not just the ones Prim and Kruskal use. The program runs the generic method 300 times, each time choosing a random cut that respects : it colours each tree of the forest randomly as "in " or "not in " (retrying if a side is empty), then adds a light crossing edge. Every run ends with weight 21, the minimum found by enumeration. It also shows what goes wrong with a crossing edge that is not light.
import random
edges = [("A", "B", 7), ("A", "D", 4), ("B", "C", 8), ("B", "D", 9), ("B", "E", 3), ("C", "E", 6),
("C", "F", 10), ("D", "E", 11), ("D", "G", 5), ("E", "F", 2), ("E", "G", 12), ("F", "G", 1)]
V = "ABCDEFG"
def components(A):
comp = {v: v for v in V}
changed = True
while changed: # simple label propagation, fine for 7 vertices
changed = False
for u, v, _ in A:
m = min(comp[u], comp[v])
if comp[u] != m or comp[v] != m:
comp[u] = comp[v] = m
changed = True
return comp
def generic_mst(rng, pick):
A = []
while len(A) < len(V) - 1:
comp = components(A)
trees = sorted(set(comp.values()))
while True:
side = {t: rng.random() < 0.5 for t in trees}
if 0 < sum(side.values()) < len(trees):
break
S = {v for v in V if side[comp[v]]}
crossing = [e for e in edges if (e[0] in S) != (e[1] in S)]
A.append(pick(rng, crossing))
return sum(w for _, _, w in A)
rng = random.Random(4)
light = lambda rng, crossing: min(crossing, key=lambda e: e[2])
results = {generic_mst(rng, light) for _ in range(300)}
print("light edges, 300 random respecting cuts: final weights", results)
anyedge = lambda rng, crossing: rng.choice(crossing)
results = sorted({generic_mst(rng, anyedge) for _ in range(300)})
print("arbitrary crossing edges: weights from", results[0], "to", results[-1])light edges, 300 random respecting cuts: final weights {21}
arbitrary crossing edges: weights from 21 to 57
Choosing an arbitrary crossing edge still produces a spanning tree (a crossing edge never closes a cycle, because its ends lie in different trees of ), but its weight can be far from minimal. Lightness is the whole point.
Note: The cut property is the greedy-choice property of the MST problem: a locally cheapest choice can always be extended to a global optimum. Spanning trees are also the bases of a graphic matroid (Matroids), and Kruskal's algorithm is exactly the matroid greedy algorithm.
Test yourself
A connected graph has 10 vertices. How many edges does every spanning tree have?
- 10
- 9
- 45
- It depends on the weights
The cut respects , and is a light edge crossing it. Which statement is the cut property?
- belongs to every MST
- is contained in some MST
- is the lightest edge of the graph
- Every edge crossing the cut is safe
In the proof of the cut property, why is the removed edge not in ?
- Because it is the heaviest edge of
- Because it crosses the cut, and no edge of crosses a cut that respects
- Because has no cycles
- Because
Why does adding any crossing edge (light or not) to never create a cycle in the generic method with a respecting cut?
- Because the graph is a tree
- Because a crossing edge joins two different trees of the forest
- Because crossing edges are always light
- It can create a cycle