Sub topic 2
The Generic Greedy MST Strategy
This chapter assumes you know graph terms (vertices, edges, cycles), edge lists, Big-O notation, and basic Python classes. It also relies on the cut property from the previous chapter. The cut property says that the lightest edge crossing any cut is safe to add to an MST.
The Generic Greedy Strategy
Every MST algorithm in this tutorial follows the same loop. Start with an empty set of edges A. While A has fewer than V−1 edges, find a safe edge and add it. An edge is safe when A plus that edge still fits inside some MST. The cut property guarantees that a safe edge always exists: pick any cut that no edge of A crosses, and take the lightest edge crossing it.
Kruskal's and Prim's algorithms differ only in which cut they pick and in the data structure that finds the lightest crossing edge quickly.
Disjoint Sets: Union by Rank and Path Compression
A disjoint-set (union-find) structure tracks which vertices are already connected. find returns a set's root. union merges two sets, and here it returns False if the two vertices already share a root. Union by rank attaches the shorter tree under the taller one. Path halving, a form of path compression, flattens trees during find. Together they make each operation run in near-constant amortized time.
Kruskal's Algorithm: Growing a Forest from Sorted Edges
Kruskal's algorithm sorts the edges by weight and keeps every edge that joins two different components. That edge is the lightest one crossing the cut between its component and the rest of the graph, so it is safe. Sorting dominates the running time: O(E log E), which equals O(E log V).
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
# Path halving: point each visited node at its grandparent.
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already in the same set; edge would form a cycle
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
return True
def kruskal(n, edges):
# edges: list of (weight, u, v) tuples with vertices numbered 0..n-1
ds = DisjointSet(n)
mst = []
total = 0
for w, u, v in sorted(edges):
if ds.union(u, v):
mst.append((u, v, w))
total += w
if len(mst) == n - 1:
break
return total, mst
edges = [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 1, 3), (5, 2, 3)]
print(kruskal(4, edges)) # (6, [(0, 1, 1), (1, 3, 2), (1, 2, 3)])Trace: the edges 0–1 (1), 1–3 (2), and 1–2 (3) each join separate components, so all three are kept. After three edges the loop stops, and edges 0–2 and 2–3 are never examined.
Priority Queues with Binary Heaps
Prim's algorithm, covered in the next chapter, needs to take out the minimum item over and over. A binary heap does that. Push and pop each take O(log n). Python's heapq keeps a list in heap order and compares tuples by their first field, which is the weight.
import heapq
heap = []
for item in [(4, "a"), (1, "b"), (3, "c")]:
heapq.heappush(heap, item)
print(heapq.heappop(heap)) # (1, 'b')Exercise
Why is the edge Kruskal accepts at each step safe according to the cut property?
Show answer
The edge joins two different components. Take the cut that separates one of those components from the rest of the graph. No accepted edge crosses that cut. Every lighter crossing edge was examined earlier and either rejected or accepted, so the current edge is the lightest one crossing the cut, which makes it safe.