Minimum spanning trees: Prim's and Kruskal's

Video lessonComing soon

1 Cables for six villages

A district wants to bring the internet to six villages. It can lay a cable between some pairs of villages, and each cable has a cost in lakh rupees. A message can pass through other villages on its way, so every village only needs some chain of cables to every other one. The engineers drew the choices as a weighted graph:

253618497012345
Nine cables the district could lay, with their costs

Laying all nine cables costs 45, and most of that is waste. The cheapest plan never has a loop. If the chosen cables formed a loop, we could drop the dearest cable on it. The villages on the loop would still reach each other the other way round, and the cost would go down.

So the best plan connects all V villages and has no loop. That makes it a tree, as in the graphs lesson, so it has exactly V − 1 edges: 5 cables here. A set of edges that connects every vertex with no cycle is a spanning tree. A spanning tree with the smallest total weight is a minimum spanning tree, or MST.

Our small map already has 55 spanning trees, and a big graph has far too many to list. So we pick good cables one at a time, which is a greedy rule. The greedy lesson showed that such a rule needs a proof before we trust it.

2 The cheapest cable across a split is safe

We split the villages into two groups, any way we like: 0, 1 and 2 on one side, 3, 4 and 5 on the other. A split like this is a cut. Any plan that connects everything must lay at least one cable across it.

The cut property says that the cheapest cable across a cut belongs to some MST. Here three cables cross. 1–3 costs 6, 2–3 costs 1, and 2–4 costs 8. The proof is an exchange argument, as in the greedy lesson. We take a plan without 2–3 and swap 2–3 in:

Swapping the cheapest crossing cable in
253618497012345
Three cables cross. 2–3 is the cheapest

The swap works for any cut. Let e be the cheapest cable across it:

  1. Take an MST that leaves out e.
  2. Adding e closes a loop. The loop crosses the cut along e, so it must cross back along another cable f.
  3. f costs at least as much as e, because e is the cheapest cable across the cut.
  4. Dropping f keeps every village connected, and the total does not go up.

The result is a spanning tree that costs no more than the MST, so it is an MST too, and it holds e. Both algorithms below use this one rule. They only choose the cut differently.

3 Kruskal: the cheapest cable first

Kruskal's algorithm sorts the cables from cheapest to dearest and looks at each one once. It lays a cable unless both ends are already connected. A cable between two connected villages would close a loop, so we skip it.

Every cable Kruskal lays is safe. When it lays u–v, we take the cut between u's piece and everything else. Every cheaper cable was looked at already, and each one now sits inside a piece, laid or skipped. So no cheaper cable crosses this cut, and u–v is the cheapest one that does.

The question "are u and v connected yet?" comes up once per cable, so it must be fast. The union-find lesson answers it. Each connected piece is a set, and unite(u, v) joins the sets of u and v. It returns false when they were one set already. So one call both checks and joins.

In the steps, each tint is one connected piece, the ringed villages are the ends of the cable we look at, and bold cables are laid.

Kruskal on the six villages
253618497012345
2–3 costs 1: lay it. Total 1

The same run as a table:

CableCostunite returnsLaid?Total
2–31trueyes1
0–12trueyes3
1–23trueyes6
3–44trueyes10
0–25falseno10
1–36falseno10
4–57trueyes17
2–48falseno17
3–59falseno17

Kruskal laid five cables, V − 1 of them, for a total of 17. Once the fifth one is laid, all six villages are one piece, so every later cable is skipped.

4 Kruskal in code

The function takes the number of villages n and the cables as rows [u, v, w]. It returns the MST's total cost. The DSU class is the union-find lesson's, with union by size and path compression.

The graph may come in more than one piece. Then Kruskal builds an MST inside each piece, a minimum spanning forest, and lays fewer than V − 1 cables. The code counts the cables it lays in used, and returns -1 when some village cannot be reached.

On the six villages, it returns 17. With a seventh village and no cable to it, it returns -1.

C++

union is a keyword, so the method is unite. The lambda tells sort to compare the third item of each row. Without it, rows sort by u first.

Compare with Integer.compare. A comparator written as a[2] - b[2] overflows when costs can be large and negative, and gives the wrong sign.

sort changes the caller's list. Use sorted(edges, key=…) if the caller still needs the old order. With union by size, a tree stays about 17 levels deep at 10⁵ villages, so the recursive find is safe.

Always pass a comparator. Without one, sort turns each row into text such as "2,3,1" and sorts the text, so rows end up ordered by u.

sort.Slice compares by index. Its function gets two positions, so it compares edges[i][2] with edges[j][2]. int is 64 bits on today's machines, so the total fits.

find takes &mut self, because path compression writes to parent. The root goes into a local root first, and then into parent[x]. The costs are i32, so as i64 converts each one before it joins the total.

Array.Sort takes a comparison. a[2].CompareTo(b[2]) sorts the rows by cost without the overflow risk of subtracting.

Cost. Sorting E cables takes O(E log E). After that, each cable needs one unite, which costs almost O(1) with union by size and path compression. So Kruskal takes O(E log E) time and O(V + E) space.

5 Prim: grow one tree

Prim's algorithm grows one tree from a start village. At each step, it lays the cheapest cable from a village in the tree to a village outside it. Here the cut is the tree against the rest, so the cut property says this cable is safe.

A min-heap finds that cable. It holds pairs (cost, village): a cable of that cost would join that village to the tree. When a village joins, we push a pair for each of its cables to a village still outside. A village can sit in the heap more than once. The first pair popped for it is its cheapest, and the later ones are stale: we skip a pair whose village is already in the tree.

In the steps, filled villages are in the tree, the ringed one has just joined, and bold cables are laid. The heap lists its pairs smallest first, with popped pairs crossed and new ones in orange.

Prim from village 0
253618497012345
(2, 1)(5, 2)
Start at 0: push (2, 1) and (5, 2)

The last two pairs, (8, 4) and (9, 5), are stale too. Prim laid the same five cables as Kruskal, in a different order, and the total is 17 again. The loop, in pseudocode:

push (0, start)
while the heap is not empty:
    pop (w, u)
    if u is in the tree: skip it
    add u to the tree, and add w to the total
    for each cable from u to v, of cost c:
        if v is not in the tree: push (c, v)

Prim against Dijkstra. This is Dijkstra's loop with one change, in what we push. Dijkstra pushes dist[u] + c, the whole drive from the source to v. Prim pushes c alone, the one cable that would join v to the tree. Prim pays only for the last cable, however far v is from the start.

6 Kruskal or Prim

Both give an MST. They differ in the input they like and in what they cost:

KruskalPrim
Input it likesa list of edgesan adjacency list
Toolssort and union-finda min-heap
TimeO(E log E)O(E log V)
Good forsparse graphs, edges given as a listdense graphs, with a plain scan

O(E log E) and O(E log V) are about the same, because E is at most V², so log E is at most 2 log V. On a sparse graph with V = 10⁵ and E = 2 × 10⁵, both take a few million steps.

Dense graphs are different. In Min Cost to Connect All Points, any two points can be joined, so 1,000 points give about 5 × 10⁵ cables. Kruskal must build all of them and sort them. Prim can skip the heap and use the scan from the Dijkstra lesson: each round reads every village outside the tree and picks the cheapest. That is O(V²), about 10⁶ steps, with no list of cables at all.

7 An MST is not a map of shortest routes

The MST keeps the total cost of the cables lowest. It does not keep any one trip short. Look at villages 3 and 5:

253618497012345
In the MST, 3 to 5 goes through 4: 4 + 7 = 11
253618497012345
The shortest route is the direct cable: 9

The direct cable 3–5 costs 9, but the MST leaves it out, because 4–5 joins village 5 for 7.

Ties. When two cables cost the same, Kruskal can take either one first. The tree may differ, but the total is the same. When all costs differ, as on our map, there is only one MST.

8 Mistakes, and when to use it

  • Sorting by the wrong field. A row is [u, v, w], and sorting rows as they are sorts by u. On our map, Kruskal then lays 0–1, 0–2, 1–3, 2–4 and 3–5, and returns 30 instead of 17.
  • Dijkstra's key in Prim. Pushing dist[u] + c and adding each popped value to the total adds up distances from village 0. It returns 0 + 2 + 5 + 6 + 10 + 15 = 38.
  • Not checking what unite returns. Code that calls unite and then adds the cost anyway lays every cable. It returns 45, the cost of all nine.
  • A 32-bit total. With 10⁵ villages and cables of up to 10⁹, the MST can cost about 10¹⁴, far past the 2 × 10⁹ an int holds. Keep the total in 64 bits.

The sign is a question that asks to connect everything at the lowest total cost: cables, roads, pipes, or points on a plane. When any two points can be joined, the graph is dense, and Prim with a scan fits. When some links are already in place, unite their ends first, at no cost, and run Kruskal on the rest.

Before coding, ask what the cost is for. The cheapest way to join everything is an MST. The cheapest route between two places is a shortest path.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.