Primero, el cuestionario del capítulo 3Primero, repasa el capítulo 3
Haz el cuestionario del capítulo 3: 10 preguntas, se aprueba con 7 correctas. Puedes repetirlo cuantas veces quieras.
The Cheapest Network
Capítulo 4, lección 2 de 2
Kruskal and Prim: connect everything for the least total cost.
Narrado en inglés. Activa arriba los subtítulos en inglés, árabe, alemán, español o francés.
Lección escrita
9 min de lecturaEscrita en inglés.
In the winter of 1925, Jindřich Saxel of the West-Moravian Powerplants brought a problem to a young mathematician in Brno, Otakar Borůvka. Dozens of villages needed electric lines. How could they all be connected with the least wire?
The answer can never contain a loop: in a loop, one line can always be removed and every village stays connected. So the cheapest network is a tree. Borůvka's paper of 1926 gave the first method to find it. Today it is called the minimum spanning tree, and two famous algorithms build it: Kruskal's and Prim's. This lesson covers why taking the cheapest edge is safe, both algorithms by hand, how they differ, and where the idea is used today.
Spanning trees
A spanning tree connects every vertex and contains no loop. With V vertices it always has exactly V − 1 edges: one fewer and some vertex is cut off, one more and there is a loop.
The minimum spanning tree (MST) is the one whose edges add up to the least. This is the example from our guides: six vertices and nine edges.
| Edge | A-C | B-C | D-E | E-F | A-B | B-D | C-D | C-E | D-F |
|---|---|---|---|---|---|---|---|---|---|
| Weight | 1 | 2 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
The best tree uses A-C, B-C, D-E, E-F and B-D, and weighs 13.
Six vertices, nine edges, and the best tree: 13.
It is not a shortest-path tree. In this tree, the route from A to F (A, C, B, D, E, F) costs 13, but the shortest path, A, C, E, F, costs 1 + 7 + 3 = 11. The tree saves wire, not travel time.
The tree minimises total wire, not any one trip.
Trying every tree is hopeless. Our small example already has 55 spanning trees, and a network where every pair of twenty villages is linked has 20¹⁸ of them (Cayley's formula from lesson 5). Yet a greedy rule, always taking the cheapest safe edge, finds the best tree every time. The reason is a single theorem.
The cut property
Split the vertices into two groups, any way you like. That split is called a cut, and some edges cross it, from one side to the other.
With A and C on one side, four edges cross: B-C 2, A-B 4, C-D 6 and C-E 7. The cheapest is B-C.
A cut, and the four edges that cross it.
Why (the exchange argument). Take a spanning tree that leaves B-C out, for example A-C, A-B, B-D, D-E, E-F, which weighs 15.
- Adding B-C closes exactly one loop: here A, C, B.
- That loop starts on one side of the cut and crosses it with B-C, so it must cross back somewhere else: here on A-B.
- Remove A-B instead. Everything is still connected, and since B-C was the cheapest crossing edge, the tree can only get lighter: 15 − 4 + 2 = 13.
So some best tree always contains the cheapest crossing edge.
Swap A-B for B-C: still connected, never heavier.
Its partner is the cycle property: the heaviest edge on any loop can be left out. One rule says which edges to take, the other which edges to throw away.
Kruskal
Kruskal's algorithm (Joseph Kruskal, 1956) sorts all the edges from cheapest to heaviest and walks down the list, taking every edge that does not close a loop. To spot a loop it asks union-find from the last lesson: are the two ends already in one group? If not, it takes the edge and merges the groups.
| Edge | Weight | Decision |
|---|---|---|
| A-C | 1 | take |
| B-C | 2 | take |
| D-E | 2 | take: starts a second group on the far side |
| E-F | 3 | take |
| A-B | 4 | skip: A and B are already linked through C |
| B-D | 5 | take: joins the two groups. Five edges, done. |
Kruskal grows a forest: two groups, and A-B closes a loop.
Kruskal grows a forest, not a tree, and the pieces merge as it goes. A-B is the heaviest edge on the loop A, B, C, so the cycle property throws it away. After B-D there are five edges for six vertices, so Kruskal stops without even looking at the three heaviest edges. Total: 13.
Five edges, total 13.
Each edge it takes is safe: when it joins two groups, no cheaper edge leaves either one, or it would have been taken already. That is the cut property, with one group on one side. Most of the work is the sort, so Kruskal runs in O(E log E).
Prim
Prim's algorithm grows a single tree instead. Start anywhere, say at A. The tree and the rest of the graph form a cut, and Prim always takes the cheapest edge across it. Each vertex outside the tree keeps a key: the cheapest edge that would attach it.
| Add | Edge | Key updates |
|---|---|---|
| C | A-C 1 | B: 4 → 2 (via C), D: 6, E: 7 |
| B | B-C 2 | D: 6 → 5 |
| D | B-D 5 | E: 7 → 2, F: 8 |
| E | D-E 2 | F: 8 → 3 |
| F | E-F 3 | total 13 |
Notice step three: B-D at 5 comes before D-E at 2, because D-E does not touch the tree yet, so Prim cannot use it. The result is the same five edges and the same 13.
Prim, round by round from A.
Every step is the cut property itself, so every edge is safe. With a heap, Prim costs about as much as Dijkstra, O((V + E) log V). Robert Prim published it in 1957, but Vojtěch Jarník had described it in 1930, in a letter to Borůvka, and Dijkstra found it again in 1959.
Which one?
Prim looks almost exactly like Dijkstra. Both keep a key for every vertex and repeatedly take the smallest. Only the key is different:
- Dijkstra: the length of a whole path from the start.
if key[u] + w < key[v] - Prim: the weight of one edge, the cheapest way to attach the vertex to the tree.
if w < key[v]
That is why negative weights are harmless to Prim: it never adds weights together. Run both from A on our example, and four of the six keys come out different:
| Vertex | A | B | C | D | E | F |
|---|---|---|---|---|---|---|
| Prim | 0 | 2 | 1 | 5 | 2 | 3 |
| Dijkstra | 0 | 3 | 1 | 7 | 8 | 11 |
Prim and Dijkstra: one line apart.
Kruskal or Prim? Kruskal is simple, and suits sparse graphs given as a list of edges. Prim with a heap suits dense graphs, where edges are many. On a graph in several pieces, Kruskal returns one tree per piece, a spanning forest, while Prim started at one vertex only spans that vertex's own piece.
Both fit in a few lines of Python:
import heapq
def kruskal(vertices, edges):
parent = {v: v for v in vertices}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
tree = []
for w, u, v in sorted(edges):
ru, rv = find(u), find(v)
if ru != rv: # no loop
parent[ru] = rv
tree.append((u, v, w))
return tree
def prim(adj, start):
in_tree, tree = {start}, []
heap = [(w, start, v) for v, w in adj[start]]
heapq.heapify(heap)
while heap:
w, u, v = heapq.heappop(heap)
if v in in_tree:
continue
in_tree.add(v)
tree.append((u, v, w))
for x, wx in adj[v]:
if x not in in_tree:
heapq.heappush(heap, (wx, v, x))
return tree
edges = [(4, "A", "B"), (1, "A", "C"), (2, "B", "C"), (5, "B", "D"), (6, "C", "D"),
(7, "C", "E"), (2, "D", "E"), (8, "D", "F"), (3, "E", "F")]
adj = {v: [] for v in "ABCDEF"}
for w, u, v in edges:
adj[u].append((v, w))
adj[v].append((u, w))
sum(w for _, _, w in kruskal("ABCDEF", edges)) # 13
prim(adj, "A") # [('A', 'C', 1), ('C', 'B', 2), ('B', 'D', 5), ('D', 'E', 2), ('E', 'F', 3)]
In the world
- Ties. When weights tie, several trees can be equally cheap: a square with four equal sides has four minimum spanning trees. If all weights differ, the best tree is unique.
- Maximum spanning tree. Sort from the heaviest instead, and the same algorithm builds the maximum spanning tree. It contains the widest route between every pair of vertices, the problem we met in lesson 12.
- Clustering. Stop Kruskal early, with two groups left, and you get the best split into two clusters: the one whose closest pair of groups is as far apart as possible. Here, A, B, C and D, E, F, five apart.
- Borůvka's method. Every group takes the cheapest edge leaving it, all at once. On our example, six groups become two, then one. The number of groups at least halves each round, which suits parallel computers.
- Networks and tours. Minimum spanning trees plan cable, pipe and road networks, and give a quick tour for the travelling salesman: walk around the tree, and on straight-line distances the tour costs at most twice the best. We will meet that in lesson 17.
Key ideas
- A minimum spanning tree connects every vertex with the least total weight, using V − 1 edges.
- The cut property makes greed safe: the cheapest edge across any cut is always in some best tree. The cycle property says the heaviest edge on a loop can go.
- Kruskal takes edges in order of weight, skipping any that close a loop (union-find). Prim grows one tree, always taking the cheapest edge that leaves it.
- That completes chapter 4: from finding groups to connecting them as cheaply as possible.
Check yourself
1. A connected graph has 12 vertices and 30 edges. How many edges does every spanning tree have?
2. In the example, the edge B-D rises from 5 to 9. What is the new minimum spanning tree weight?
3. Why does Prim not care about negative weights, while Dijkstra does?
Practice on the platform
The guide to Prim's algorithm traces this same example round by round, and the minimum spanning trees guide compares both algorithms. In the Prim visualizer, import the nine edges and run it from A: A-C, B-C, B-D, D-E and E-F, total thirteen, exactly as by hand.
A continuación