Sub topic 6
The Generic Greedy MST Strategy
The earlier chapters proved two facts about minimum spanning trees. The cut property says that the lightest edge crossing a cut can safely join an MST. The cycle property says that the heaviest edge on a cycle can be left out. This chapter turns the cut property into one general algorithm. Kruskal's and Prim's algorithms both follow it. Once you see the general version, each of them reduces to a single question: how does it pick the next cut?
This chapter assumes you know graph terms (vertex, edge, path, cycle, connected component), edge-list representations, Big-O notation, and basic Python. It also assumes you have read the chapters on the MST definition and the cut property. That proof is not repeated here.
The Invariant That Drives Everything
The generic algorithm builds a set of edges A one edge at a time. Every step keeps this invariant true:
- Invariant:
Ais a subset of some minimum spanning tree.
At the start, A is empty, and the empty set is a subset of every MST. If each step adds an edge that keeps the invariant true, then after V - 1 additions A is a spanning tree contained in an MST. A spanning tree has exactly V - 1 edges, so A is that MST.
An edge that keeps the invariant true is called a safe edge for A. The whole algorithm then fits in a few lines:
- Set
Ato the empty set. - While
Ahas fewer thanV - 1edges: - Find an edge
(u, v)that is safe forA. - Add it to
A. - Return
A.
As written, the loop doesn't say how to find a safe edge. The cut property supplies the method.
Finding a Safe Edge with a Cut
A cut (S, V − S) splits the vertices into two groups. An edge crosses the cut if one endpoint is in S and the other is in V − S. A cut respects A if no edge of A crosses it. A light edge for a cut is a crossing edge whose weight is minimal among all crossing edges. When weights tie, more than one edge can be light.
The cut property, stated in the form the algorithm uses:
- If
Ais a subset of some MST, the cut(S, V − S)respectsA, and(u, v)is a light edge crossing that cut, then(u, v)is safe forA.
That gives a concrete recipe for each iteration:
- Choose any cut that respects
A. - Take a light edge crossing it.
- Add that edge to
A.
What A Looks Like Mid-Run
A never contains a cycle, because it is part of a tree. So at every moment A is a forest: a set of trees, which can include single vertices with no edges. A cut respects A exactly when no tree of that forest is split by it. Each tree sits wholly inside S or wholly inside V − S.
That observation makes the cut easy to pick. Take one component of the forest, or a union of several components, and call it S. Any edge crossing the resulting cut joins two different components, so adding it can never create a cycle. Each addition merges two components into one. A forest that starts with V components therefore needs exactly V - 1 merges to become one tree.
A Runnable Generic Implementation
The code below implements the generic strategy directly. Speed is not the goal here. The choose parameter decides which component becomes S, so you can watch different cut choices produce the same total weight.
def generic_mst(n, edges, choose=lambda labels: labels[0]):
# edges: list of (weight, u, v) tuples, vertices numbered 0..n-1
# choose: picks one component label; that component becomes S
comp = list(range(n)) # comp[v] is the label of v's tree in the forest A
A = []
while len(A) < n - 1:
labels = sorted(set(comp))
s_label = choose(labels)
# Find a light edge crossing the cut (S, V - S).
best = None
for w, u, v in edges:
crosses = (comp[u] == s_label) != (comp[v] == s_label)
if crosses and (best is None or w < best[0]):
best = (w, u, v)
if best is None:
raise ValueError("graph is disconnected; no edge crosses the cut")
w, u, v = best
A.append((u, v, w))
# Merge the two trees joined by the new edge.
old, new = comp[v], comp[u]
for i in range(n):
if comp[i] == old:
comp[i] = new
return sum(w for _, _, w in A), A
edges = [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 1, 3), (5, 2, 3)]
print(generic_mst(4, edges))
# (6, [(0, 1, 1), (1, 3, 2), (1, 2, 3)])
print(generic_mst(4, edges, choose=lambda labels: labels[-1]))
# (6, [(1, 3, 2), (1, 2, 3), (0, 1, 1)])Each iteration scans every edge and relabels every vertex, so this version runs in O(V · (E + V)) time. The later chapters bring that down. Kruskal's algorithm uses a disjoint-set structure to answer "same component?" quickly. Prim's algorithm uses a heap to find the light edge quickly.
Tracing Both Runs
The first run always picks the component with the smallest label. Vertex 0 is always in that component, so S is the tree that contains vertex 0:
| Step | S | Crossing edges (weight) | Light edge | A after step |
|---|---|---|---|---|
| 1 | {0} | 0–1 (1), 0–2 (4) | 0–1 (1) | {0–1} |
| 2 | {0, 1} | 0–2 (4), 1–2 (3), 1–3 (2) | 1–3 (2) | {0–1, 1–3} |
| 3 | {0, 1, 3} | 0–2 (4), 1–2 (3), 2–3 (5) | 1–2 (3) | {0–1, 1–3, 1–2} |
The second run picks the component with the largest label:
| Step | S | Crossing edges (weight) | Light edge | A after step |
|---|---|---|---|---|
| 1 | {3} | 1–3 (2), 2–3 (5) | 1–3 (2) | {1–3} |
| 2 | {2} | 0–2 (4), 1–2 (3), 2–3 (5) | 1–2 (3) | {1–3, 1–2} |
| 3 | {1, 2, 3} | 0–1 (1), 0–2 (4) | 0–1 (1) | {1–3, 1–2, 0–1} |
The two runs add edges in different orders and choose different cuts, but both end with total weight 6. The cut property guarantees this. Every edge added was light for some cut that respected A.
Kruskal, Prim, and Borůvka as Cut Choices
Every classic MST algorithm is this loop with a specific rule for picking the cut.
| Algorithm | Cut it uses | How it finds the light edge |
|---|---|---|
| Prim | `S` = the single tree grown from the start vertex | A priority queue of edges leaving the tree |
| Kruskal | `S` = the tree containing one endpoint of the globally lightest edge that joins two different trees | Scan the edges in sorted order and skip any edge whose endpoints are already in the same tree |
| Borůvka | Every tree is its own `S`, all at once | Each tree picks its lightest outgoing edge, and all of those edges are added in one round |
Kruskal's algorithm needs one more step of reasoning to fit the pattern. Suppose Kruskal's algorithm considers edge (u, v) and finds that u and v are in different trees. Let S be the tree containing u. Every edge lighter than (u, v) has already been processed. Each one was either added to A or skipped because its endpoints were in the same tree. Neither kind crosses this cut. So (u, v) is light for the cut, and the cut property applies.
The first run of generic_mst follows Prim's pattern. Each step grows one tree from vertex 0.
Edge Cases and Common Errors
Ties in Weight
If several crossing edges share the minimum weight, any one of them is safe. Different tie-breaks can produce different MSTs, all with the same total weight. The uniqueness chapter covers this in detail.
Borůvka's algorithm needs extra care with ties because it adds several edges in the same round. Suppose a triangle has three edges of equal weight. Each vertex might pick a different edge, and the round would add all three edges, forming a cycle. The fix is to break ties consistently, for example by comparing (weight, edge_id) pairs. That makes every weight distinct.
Cuts That Do Not Respect A
The cut property only applies to cuts that respect A. If an edge of A crosses the cut, the light crossing edge may already be in A. Worse, it may connect two vertices that A already joins, so adding it creates a cycle. This is why generic_mst builds S from whole components and never from an arbitrary set of vertices.
The Lightest Edge at a Single Vertex
The cut ({v}, V − {v}) respects the empty set. So for any vertex v, the lightest edge touching v belongs to some MST. People sometimes stretch this into a false rule: "take the lightest edge at every vertex and you have the MST." Those edges belong to some MST, but the result has fewer than V - 1 edges in general. Without careful tie-breaking, the edges may even come from different MSTs. Borůvka's algorithm starts with this step and then repeats it on the merged components.
Disconnected Graphs
If the graph is disconnected, at some point no edge crosses the chosen cut, and generic_mst raises an error. The chapter on minimum spanning forests shows how to stop cleanly and return one tree per component.
Weights Do Not Need to Be Positive
The cut property compares weights only with each other. Negative or zero weights cause no problems. Self-loops never cross a cut, so the algorithm ignores them. When parallel edges join the same pair of vertices, only the lightest of them can be chosen.
Greedy Choices That Look Similar but Fail
The greedy choice works for MSTs because of the cut property. It does not carry over to related problems. Two common mistakes:
- Picking the edge with the smallest distance from the start vertex produces a shortest-path tree, which is Dijkstra's algorithm. A shortest-path tree is generally not an MST.
- The greedy strategy can fail when the tree must meet an extra constraint, such as a maximum degree per vertex or a required set of edges. The safe-edge argument assumes that any spanning tree is allowed.
Exercise
In the graph with edges 0–1 (1), 0–2 (4), 1–2 (3), 1–3 (2), 2–3 (5), suppose A = {0–1}. Is the cut S = {0, 2} valid for the generic algorithm? If not, give a cut that respects A and contains vertex 2 in S, and name its light edge.
Show answer
No. Edge 0–1 is in A, and it crosses the cut because vertex 0 is in S and vertex 1 is not. A valid choice is S = {2}. Its crossing edges are 0–2 (4), 1–2 (3), and 2–3 (5), so the light edge is 1–2 with weight 3. Another valid choice is S = {0, 1, 2}. Its crossing edges are 1–3 (2) and 2–3 (5), so the light edge is 1–3 with weight 2.
Exercise
A student proposes this algorithm: "Repeatedly pick the lightest remaining edge in the graph and add it to A, unless both of its endpoints already have at least one edge in A." Is this an instance of the generic greedy strategy? Test it on the path-plus-chord graph with edges a–b (1), c–d (1), b–c (5), a–d (6).
Show answer
No. The rule ignores which components the endpoints belong to. The algorithm adds a–b and c–d. Next it considers b–c, and both b and c already have an edge in A, so it skips b–c. The same happens to a–d. A ends with two edges, which is not a spanning tree. The rule fails because it doesn't test whether an edge crosses a cut that respects A. The correct test asks whether the endpoints are in different trees, and that test would accept b–c with weight 5.
Exercise
Change generic_mst so that choose always returns the label of the component containing vertex 3. Without running the code, list the edges in the order they are added for the sample graph, and give the total weight.
Show answer
S starts as {3}, with crossing edges 1–3 (2) and 2–3 (5), so the algorithm adds 1–3. Then S = {1, 3}, with crossing edges 0–1 (1), 1–2 (3), and 2–3 (5), so it adds 0–1. Then S = {0, 1, 3}, with crossing edges 0–2 (4), 1–2 (3), and 2–3 (5), so it adds 1–2. The order is 1–3, 0–1, 1–2, and the total weight is 6.