Connectivity, flow and routes · 30 / 53
Prim, Kruskal and disjoint set union
Understand → trace → implement → justify
1 min reading · allow extra time for practiceA spanning tree connects all vertices without cycles using V−1 edges. MST minimises total tree weight, not every root-to-vertex distance. Disconnected graphs yield spanning forests; negative weights are allowed.
The cut property justifies a cheapest crossing edge. Prim grows one tree through its cheapest crossing edge; Kruskal sorts edges and joins distinct components. Equal weights can produce multiple valid MSTs.
DSU supplies find and union. Path compression plus union by rank/size gives amortised O(α(n)) over operation sequences, not literally constant complexity. Arbitrary deletion needs different machinery; rollback DSU uses different compression policies.
A worked trace
AB1,BC2,AC5: Kruskal choosesAB andBC, rejectingAC as a cycle. Total3; agreement with shortest paths here is incidental.
Cost and assumptions
Kruskal O(E log E) sorting plus O(E α(V)) DSU work; binary-heap Prim O(E log V).
Executable example
Run with Python 3. Assertions check a small example; they do not constitute a general correctness proof. Some advanced examples are explicitly small models or reference oracles, not full production implementations.
class DSU:
def __init__(self, n): self.p=list(range(n)); self.size=[1]*n
def find(self, x):
while self.p[x] != x:
self.p[x] = self.p[self.p[x]]; x = self.p[x]
return x
def union(self, a, b):
a,b = self.find(a), self.find(b)
if a == b: return False
if self.size[a] < self.size[b]: a,b=b,a
self.p[b]=a; self.size[a]+=self.size[b]
return True
d=DSU(3)
assert d.union(0,1) and d.union(1,2) and not d.union(0,2)TEST YOUR UNDERSTANDING
Your turn
Why is removing an edge from DSU difficult?
Reveal the reasoning
Union summarises connectivity without retaining all alternate paths. Deletion requires separate dynamic-connectivity machinery.
Take it further
- Write down the input contract and the invariant before changing the example.
- Add empty, boundary, duplicate and adversarial cases where they are relevant. Compare with a simple oracle.
- Derive the cost under the stated model; measure several input sizes and explain discrepancies.
Primary reading & lecture notes
Original explanations in this course; these references provide proofs and further reading. Source links may cover the broader module.
Princeton · Algorithms, Sedgewick & Wayne ↗Jeff Erickson · Algorithms ↗