Minimum spanning trees: Prim and Kruskal
A minimum spanning tree joins all n vertices with n − 1 edges of least total weight: Prim grows from one vertex, adding the nearest each time, and Kruskal takes edges short to long after a sort, skipping cycles with union-find.
Six villages need internet, and laying fibre between any two of them costs a different amount. Not every pair needs a direct line; the villages just have to be connected as a whole. What is the cheapest plan? Connecting n villages takes at least n − 1 lines; one more makes a cycle, and dropping the most expensive edge on that cycle keeps everything connected and saves money. So we want n − 1 edges that connect every vertex with the smallest total weight. This is a minimum spanning tree (MST). Power grids, pipelines, circuit-board wiring and clustering algorithms all use it.
Prim: grow out from one vertex
Prim is like Dijkstra: a tree starts at one vertex, and each time the vertex nearest the tree is attached, together with that edge. lowcost[v] holds "the shortest edge from v to any vertex already in the tree":
- Put the start in the tree and fill lowcost from its edges.
- Repeat n − 1 times: take the vertex v not in the tree with the smallest lowcost, attach it and that edge; then use v's edges to update the other vertices' lowcost (only when smaller).
The only difference from Dijkstra: Dijkstra compares dist[u] + w (the distance to the start), Prim compares just w (the distance to the tree).
Each round scans lowcost for the smallest and scans again to update, for n rounds: O(n²), whatever the number of edges. So the array version of Prim suits dense graphs. You will write its code in the practice; it is almost the same as last lesson's array Dijkstra.
Edges A–B 3, A–C 1, B–C 2, B–D 4, C–D 5, D–E 2, C–E 6. Running Prim from A, in what order do edges join the tree?
A–C B–C D–E B–D is Kruskal's order: D–E is only 2, but at first neither end is in the tree, so Prim can't reach it.Prim with the lowcost array is O(n²). What kind of graph does it suit best?
Write Prim
✓Complete each round of the array Prim: among the vertices not in the tree, take v with the smallest lowcost, print from[v]-v, add the weight, mark it as in the tree; then use v's edges to update lowcost and from.
0-2 2-4 4-3 2-1 3-5 18
1#include <iostream>2#include <vector>3using namespace std;4 5const int INF = 1000000000;6 7int main() {8 int n = 6;9 vector<vector<int>> w(n, vector<int>(n, INF));10 auto add = [&](int u, int v, int c) { w[u][v] = w[v][u] = c; };11 add(0, 1, 6); add(0, 2, 1); add(1, 2, 4); add(1, 3, 5); add(2, 3, 7);12 add(2, 4, 3); add(3, 4, 2); add(3, 5, 8); add(4, 5, 9);13 vector<bool> in(n, false);14 vector<int> lowcost(w[0]), from(n, 0); // lowcost starts as row 015 int total = 0;16 in[0] = true;17 for (int k = 1; k < n; k++) {18 int v = -1;19 // 1. among those not in the tree, find v with the smallest lowcost20 // 2. print from[v]-v, add lowcost[v] to total, in[v] = true21 // 3. for each j not in the tree: if w[v][j] < lowcost[j], update lowcost[j] and from[j]22 }23 cout << "\n" << total << "\n";24 return 0;25}
Kruskal: edges from short to long, take any that makes no cycle
Kruskal looks at it another way: never mind where the tree grows; sort all edges by weight from small to large and look at them one by one. If the two ends are not yet connected, take the edge; if they already are, taking it would make a cycle, so skip it. Stop after n − 1 edges.
The sorted edges: 0–2 (1), 3–4 (2), 2–4 (3), 1–2 (4), 1–3 (5), 0–1 (6), 2–3 (7), 3–5 (8), 4–5 (9).
Sorting is O(e log e), and checking each edge's ends afterwards is almost O(1) (thanks to union-find, the next level), so Kruskal is O(e log e) and suits sparse graphs.
What if we don't check for cycles and just take the shortest n − 1 edges?
1#include <iostream>2#include <vector>3using namespace std;4 5struct Edge { int u, v, w; };6 7int main() {8 // the 9 edges, already sorted by weight9 vector<Edge> e = {{0, 2, 1}, {3, 4, 2}, {2, 4, 3}, {1, 2, 4}, {1, 3, 5},10 {0, 1, 6}, {2, 3, 7}, {3, 5, 8}, {4, 5, 9}};11 int total = 0;12 bool touches5 = false;13 for (int i = 0; i < 5; i++) { // just take the shortest 514 cout << e[i].u << "-" << e[i].v << "(" << e[i].w << ") ";15 total += e[i].w;16 if (e[i].u == 5 || e[i].v == 5) touches5 = true;17 }18 cout << "\ntotal " << total << ", less than 18\n";19 cout << "is vertex 5 connected: " << (touches5 ? "yes" : "no") << "\n";20 return 0;21}
0-2(1) 3-4(2) 2-4(3) 1-2(4) 1-3(5) total 15, less than 18 is vertex 5 connected: no
A total of 15 looks cheaper, but 1–2, 2–4, 3–4 and 1–3 form a cycle: one of the 5 edges is wasted, and vertex 5 is not connected. Every edge must first ask: are its two ends already connected?
The same graph: Edges A–B 3, A–C 1, B–C 2, B–D 4, C–D 5, D–E 2, C–E 6. In what order does Kruskal pick edges?
Same graph again. Which is the first edge Kruskal skips?
Union-find: are two vertices connected?
Kruskal keeps asking "are u and v in the same block?" and "join these two blocks". Union-find (also called DSU, disjoint set union) does exactly that: each block is a tree, stored in a vector<int> parent where each vertex points to its parent and a root points to itself.
find(x): follow parent up to the root. Two vertices with the same root are in the same block.unite(a, b): find both roots and hang one under the other.
Trees can grow tall, and find then walks a long way. Use two ideas together:
- Path compression: once find reaches the root, point every vertex it passed straight at the root, so next time it is one step.
- Union by size: keep a second vector
szwith the number of vertices in each block; when joining, hang the smaller under the bigger, so the tree never grows lopsided.
With both, each operation costs almost a constant on average (strictly O(α(n)), where α grows so slowly that it stays below 5 even when n is the number of atoms in the universe).
As a class, with parent and sz as its members. An edge is a struct Edge, and sorting is sort with a lambda:
1#include <iostream>2#include <vector>3#include <algorithm>4#include <numeric>5using namespace std;6 7struct Edge { int u, v, w; };8 9class DSU {10public:11 vector<int> parent, sz;12 DSU(int n) : parent(n), sz(n, 1) {13 iota(parent.begin(), parent.end(), 0); // parent[i] = i14 }15 int find(int x) { // find the root, pointing everything on the way at it16 if (parent[x] != x)17 parent[x] = find(parent[x]);18 return parent[x];19 }20 bool unite(int a, int b) { // false if already connected21 a = find(a);22 b = find(b);23 if (a == b) return false;24 if (sz[a] < sz[b]) swap(a, b); // the smaller goes under the bigger25 parent[b] = a;26 sz[a] += sz[b];27 return true;28 }29};30 31int main() {32 int n = 6;33 vector<Edge> e = {{0, 1, 6}, {0, 2, 1}, {1, 2, 4}, {1, 3, 5}, {2, 3, 7},34 {2, 4, 3}, {3, 4, 2}, {3, 5, 8}, {4, 5, 9}};35 sort(e.begin(), e.end(), [](const Edge& a, const Edge& b) { return a.w < b.w; });36 DSU d(n);37 int picked = 0, total = 0;38 for (const Edge& x : e) {39 if (picked == n - 1) break;40 if (!d.unite(x.u, x.v)) {41 cout << "skip " << x.u << "-" << x.v << "(" << x.w << "): makes a cycle\n";42 continue;43 }44 picked++;45 total += x.w;46 cout << "take " << x.u << "-" << x.v << "(" << x.w << ")\n";47 }48 cout << "total " << total << "\nparent: ";49 for (int p : d.parent) cout << p << " ";50 d.find(4);51 cout << "\nafter find(4): ";52 for (int p : d.parent) cout << p << " ";53 cout << "\n";54 return 0;55}
take 0-2(1) take 3-4(2) take 2-4(3) take 1-2(4) skip 1-3(5): makes a cycle skip 0-1(6): makes a cycle skip 2-3(7): makes a cycle take 3-5(8) total 18 parent: 0 0 0 0 3 0 after find(4): 0 0 0 0 0 0
Edges 1–3 (5), 0–2 (3), 0–1 (1), 2–3 (4), 1–2 (2): what is the total weight of the minimum spanning tree?
1#include <iostream>2#include <vector>3#include <algorithm>4#include <numeric>5using namespace std;6 7struct Edge { int u, v, w; };8 9class DSU {10public:11 vector<int> parent, sz;12 DSU(int n) : parent(n), sz(n, 1) { iota(parent.begin(), parent.end(), 0); }13 int find(int x) {14 if (parent[x] != x) parent[x] = find(parent[x]);15 return parent[x];16 }17 bool unite(int a, int b) {18 a = find(a);19 b = find(b);20 if (a == b) return false;21 if (sz[a] < sz[b]) swap(a, b);22 parent[b] = a;23 sz[a] += sz[b];24 return true;25 }26};27 28int main() {29 vector<Edge> e = {{1, 3, 5}, {0, 2, 3}, {0, 1, 1}, {2, 3, 4}, {1, 2, 2}};30 sort(e.begin(), e.end(), [](const Edge& a, const Edge& b) { return a.w < b.w; });31 DSU d(4);32 int total = 0;33 for (const Edge& x : e)34 if (d.unite(x.u, x.v)) total += x.w;35 cout << total << "\n";36 return 0;37}
6 vertices start as roots (parent[i] = i). Do union(0, 1), union(2, 3), union(1, 3) in turn, where union(a, b) is parent[find(a)] = find(b). What is the parent array now?
What should Kruskal do with an edge whose ends are already connected? Pick one so the program prints the minimum spanning tree's total, 18.
1#include <iostream>2#include <vector>3#include <algorithm>4#include <numeric>5using namespace std;6 7struct Edge { int u, v, w; };8 9vector<int> parent(6);10 11int find(int x) {12 if (parent[x] != x) parent[x] = find(parent[x]);13 return parent[x];14}15 16int main() {17 vector<Edge> e = {{0, 1, 6}, {0, 2, 1}, {1, 2, 4}, {1, 3, 5}, {2, 3, 7},18 {2, 4, 3}, {3, 4, 2}, {3, 5, 8}, {4, 5, 9}};19 sort(e.begin(), e.end(), [](const Edge& a, const Edge& b) { return a.w < b.w; });20 iota(parent.begin(), parent.end(), 0);21 int total = 0;22 for (const Edge& x : e) {23 int a = find(x.u), b = find(x.v);24 if (a == b) ;25 parent[a] = b;26 total += x.w;27 }28 cout << total << "\n";29 return 0;30}
continue. With break, it stops at 1–3, the first edge that makes a cycle, before 5 is connected, and the total is only 10.Count blocks with union-find
✓Complete the DSU's find (with path compression) and unite (union by size: hang the smaller root under the bigger one and add its sz). After a few unites the program counts the roots (parent[i] == i), which is the number of blocks, and asks how many vertices are in 0's block.
3 blocks; 0 and 2 connected; 0's block has 4
1#include <iostream>2#include <vector>3#include <numeric>4#include <algorithm>5using namespace std;6 7class DSU {8public:9 vector<int> parent, sz;10 DSU(int n) : parent(n), sz(n, 1) { iota(parent.begin(), parent.end(), 0); }11 int find(int x) {12 // if parent[x] is not x, parent[x] = find(parent[x]); then return parent[x]13 return x;14 }15 void unite(int a, int b) {16 // replace a and b by their roots; return if equal; hang the root with the smaller sz under the other, add the sz17 }18 int size(int x) { return sz[find(x)]; }19};20 21int main() {22 DSU d(8);23 d.unite(0, 1); d.unite(2, 3); d.unite(1, 3); d.unite(5, 6); d.unite(6, 7);24 int blocks = 0;25 for (int i = 0; i < 8; i++)26 if (d.parent[i] == i) blocks++;27 cout << blocks << " blocks; 0 and 2 " << (d.find(0) == d.find(2) ? "connected" : "not connected");28 cout << "; 0's block has " << d.size(0) << "\n";29 return 0;30}
With the STL
The STL has no union-find and no minimum spanning tree; the 20-line DSU class from the previous level is what everyone writes by hand. Two things it does give you:
sortwith a comparison: Kruskal's edge sort.sortis introsort (mostly quicksort, switching to heapsort when it gets too deep and to insertion sort for short runs), O(e log e). The lambda[](const Edge& a, const Edge& b) { return a.w < b.w; }must be a "strictly less than"; writing<=is undefined behaviour.priority_queue: Prim's "find the vertex nearest the tree" becomes a min-heap, just like last lesson's heap Dijkstra. The heap holds(edge weight, vertex), and anything popped that is already in the tree is skipped.
1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5#include <utility>6using namespace std;7 8const int INF = 1000000000;9typedef pair<int, int> P;10 11int main() {12 int n = 6;13 vector<vector<P>> g(n); // g[u] holds (v, w)14 auto add = [&](int u, int v, int w) {15 g[u].push_back({v, w});16 g[v].push_back({u, w});17 };18 add(0, 1, 6); add(0, 2, 1); add(1, 2, 4); add(1, 3, 5); add(2, 3, 7);19 add(2, 4, 3); add(3, 4, 2); add(3, 5, 8); add(4, 5, 9);20 21 vector<int> lowcost(n, INF), from(n, -1);22 vector<bool> in(n, false);23 priority_queue<P, vector<P>, greater<P>> pq; // (weight to the tree, vertex)24 lowcost[0] = 0;25 pq.push({0, 0});26 int total = 0, pops = 0;27 while (!pq.empty()) {28 int w = pq.top().first, v = pq.top().second;29 pq.pop();30 pops++;31 if (in[v]) continue; // already in the tree: stale32 in[v] = true;33 total += w;34 if (from[v] != -1) cout << from[v] << "-" << v << " ";35 for (const P& e : g[v])36 if (!in[e.first] && e.second < lowcost[e.first]) {37 lowcost[e.first] = e.second;38 from[e.first] = v;39 pq.push({e.second, e.first});40 }41 }42 cout << "\ntotal " << total << ", " << pops << " pops\n";43 return 0;44}
0-2 2-4 4-3 2-1 3-5 total 18, 9 pops
The edges come out in the same order as with the array. Each edge enters the heap at most once, O(e log e) = O(e log n): faster than O(n²) on a sparse graph, while on a dense graph (e close to n²) the array version wins.
Kruskal sorts its edges with sort(e.begin(), e.end(), [](const Edge& a, const Edge& b) { … }). Which line goes inside the braces?
<. <= makes comp(x, x) true, which is undefined behaviour; a.w - b.w is how C's qsort wants it, but here it is read as a bool, true whenever the two differ, so the order comes out scrambled; > sorts the edges from long to short and picks the spanning tree with the largest total.Prim or Kruskal?
Both algorithms find a minimum spanning tree. Exams and interviews like to ask when to use which, along with a few facts that are easy to mix up.
| Prim | Kruskal | |
|---|---|---|
| How it grows | one tree grows from one vertex | many blocks, merged as edges are taken |
| Each step | attach the vertex nearest the tree | the next shortest edge, taken if it makes no cycle |
| Uses | a lowcost array, or a priority_queue | sort + union-find |
| Time | O(n²); with a heap O(e log n) | O(e log e) |
| Suits | dense graphs | sparse graphs |
When all edge weights differ, the minimum spanning tree is unique and both algorithms pick the same edges; with equal weights there may be several, all with the same total.
In interviews: "min cost to connect all points" and "connect all cities at minimum cost" are minimum spanning trees, and Kruskal is the easiest to write: sort the edges, plus a union-find. Union-find also comes up on its own ("number of provinces", "redundant connection", "accounts merge"), so be ready to write find / unite with path compression and union by size on the spot. Exams ask for "the order in which Prim (from a given vertex) / Kruskal picks edges", and "is the path between two vertices in an MST a shortest path?" (no, that is Dijkstra's job).
In a connected graph, all the edge weights are different. How many minimum spanning trees does it have?
The triangle A–B 2, B–C 2, A–C 3 has minimum spanning tree A–B and B–C. In the tree, the path from A to C is 4 long. What's the shortest path from A to C in the graph?
Summary
Minimum spanning tree: n − 1 edges, connected, smallest total
- Prim: grow from one vertex, each time attach the one nearest the tree; array O(n²) for dense graphs, priority_queue O(e log n)
- Kruskal: sort edges from short to long, take one only if its ends aren't connected; O(e log e), sparse graphs
- Union-find: find gets the root with path compression, unite hangs the smaller root under the bigger
- Without the cycle check you pick a cycle and miss vertices
1int find(int x) {2 if (parent[x] != x) parent[x] = find(parent[x]);3 return parent[x];4}5a = find(a); b = find(b); if (a == b) return false;6if (sz[a] < sz[b]) swap(a, b); parent[b] = a; sz[a] += sz[b];