Given an undirected graph G = (V, E), and a weight function w(u,v) for each edge (u,v) ∈ E, find an acyclic subset T ⊆ E that connects all of the vertices whose total weight
w(T) = Σ(u,v)∈T w(u,v)
is minimized.
Generic-MST(G, w) 1 A = φ 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 A
Invariant: Prior to each iteration, A is a subset of some minimum spanning tree.
Safe edge: An edge that may be added to A without violating the invariant that A is a subset of some minimum spanning tree.
Cut: is a partition of V into S and V−S.
Crossing: An edge (u,v) ∈ E crosses the cut (S, V−S) if one of its endpoints is in S and the other is in (V−S).
Respecting: A cut respects a set A of edges if no edge in A crosses the cut.
Light edge: An edge is a light edge crossing a cut if its weight is the minimum of any edge crossing the cut. Note that there may be more than one light edge.
Theorem Let G = (V, E) be a connected, undirected graph with a real-valued weight function w defined on E. Let A be a subset of E that is included in some minimum spanning tree for G, let (S, V−S) be any cut of G that respects A, and let (u,v) be a light edge crossing (S, V−S). Then edge (u, v) is safe for A.
Proof
Consider the set:
{(u,v) : there exists a cut (S, V−S) such that (u,v) is a light edge crossing it}
Does this set form a minimum spanning tree?
MST-Prim (G, w, r) 1 for each u ∈ G.V 2 u.key = ∞ 3 u.π = NIL 4 r.key = 0 5 Q = G.V 6 while Q ≠ φ 7 y = Extract-Min(Q) 8 for each v ∈ G.Adj[u] 9 if v ∈ Q and w(u,v) < v.key 10 v.π = u 11 v.key = w(u,v)
MST-Prim (G, w, r) 1 for each u ∈ G.V 2 u.key = ∞ 3 u.π = NIL 4 r.key = 0 5 Q = G.V 6 while Q ≠ φ 7 y = Extract-Min(Q) 8 for each v ∈ G.Adj[u] 9 if v ∈ Q and w(u,v) < v.key 10 v.π = u 11 v.key = w(u,v)
Total running time = O(V log(V) + E log(V)) = O(E log(V))
Make-Set(x)
1 x.p = x
2 x.rank = 0
Union(x, y) 1 Link(Find-Set(x), Find-Set(y))
Link(x, y)
1 if x.rank > y.rank
2 y.p = x
3 else
x.p = y
4 if x.rank == y.rank
5 y.rank = y.rank + 1
Find-Set(x) 1 if x ≠ x.p 2 x.p = Find-Set(x.p) 3 return x.p
MST-Kruskal 1 A = φ 2 for each vertex v ∈ G.V 3 Make-Set(v) 4 sort the edges of G.E into nondecreasing order by weight w 5 for each edge (u,v) ∈ G.E, taken in nondecreasing order by weight 6 if Find-Set(u) ≠ Find-Set(v) 7 A = A ∪ {(u,v)} 8 Union(u,v) 9 return A
Running time = O(E⋅log(V)), using union-find data structure for disjoint sets, with path compression