CAP7004 · Unit 6: Graphs
Minimum spanning trees and union-find
8 practice questions
Key points
- Spanning tree: V-1 edges, connected, acyclic
- Kruskal sorts edges and uses union-find
- Prim grows from a vertex using a min-heap
- Path compression + union by rank make union-find near O(1)
A spanning tree of a connected graph on V vertices uses V - 1 edges and connects all vertices without a cycle. The minimum spanning tree (MST) has the smallest total weight.
Kruskal's algorithm (greedy, edges):
- Sort edges by weight.
- Take each edge if it connects two different components (no cycle); skip otherwise.
- Stop at V - 1 edges.
Time O(E log E) (the sort dominates).
Prim's algorithm (greedy, vertices): grow one tree from a start vertex, always adding the cheapest edge leaving the tree (uses a min-heap). Time O(E log V).
Worked example: edges A-B 1, A-C 2, B-C 3, C-D 4, B-D 5. Kruskal takes A-B (1), A-C (2), skips B-C (it would make a cycle), takes C-D (4): total 7 with 3 edges. Prim from A also gives 7.
Union-find (disjoint set union) tracks components for Kruskal: find(x) returns the set representative; union(a, b) merges sets. With path compression and union by rank each operation is almost O(1) (amortized inverse Ackermann).
Properties: if all edge weights are distinct the MST is unique. The MST of a graph on V vertices always has exactly V - 1 edges.
Exam pitfall: MST minimises total weight, not the distance between particular vertices (that is shortest path).
Try two questions
Edges A-B 1, A-C 2, B-C 3, C-D 4, B-D 5. The weight of the minimum spanning tree is:
- 10
- 7
- 6
- 8
Show the answer
B. Kruskal picks [('A', 'B', 1), ('A', 'C', 2), ('C', 'D', 4)]: total 7.
Prim's algorithm grows the tree by repeatedly adding:
- The cheapest edge leaving the current tree
- The heaviest edge not forming a cycle
- The cheapest edge in the whole graph
- A random edge
Show the answer
A. At each step the lightest edge that crosses from the tree to outside is safe.