Minimum Spanning Trees

Six towns, ten possible cables. The five cheapest cables cost 15, but they close a loop and leave one town dark. Kruskal and Prim each find the cheapest network that reaches every town: 17.

Pick a rule and press Play. Watch which cables each rule takes, in which order. Then we build, piece by piece, the cut property that makes greed safe, Kruskal, Prim, their costs, and three uses.

You need a little Python and the idea of a graph (dots joined by lines). Greedy algorithms and disjoint sets help. We build the rest from zero.

Based on Chapter 23, Minimum Spanning Trees, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: Elementary Graph Algorithms. Next: Single-Source Shortest Paths.

Connect six towns three ways

Illustrative network: we made up the towns and the ten prices, and every chapter uses them. Green cables stay. A red cable closes a loop. Prim starts at town A.

Chapter 0

Five Cables for Six Towns

Connect every town for the least money, and see why the cheapest cables alone fail

You lay fibre between six towns, A to F. Surveyors priced ten possible routes. Every town must reach every other town through some chain of cables. You want the smallest total bill.

Model it as a graph: each town is a vertex, each route is an edge, and each price is the edge's weight. A set of edges that reaches every vertex and has no loop is a spanning tree. The spanning tree with the smallest total weight is the minimum spanning tree, or MST.

A spanning tree on n towns always has n − 1 edges. With fewer, some town is cut off. One more edge closes a loop, and any cable on a loop can go without cutting anyone off. So six towns need exactly five cables. Which five?

Pick the cables yourself

Tap a cable on the map or a chip below to take it or drop it. Try to reach all six towns for the smallest bill.

Illustrative prices. Green: your cable is in a network that spans and has no loop. Red: this cable closes a loop.

Take the cheapest five: 1, 2, 3, 4 and 5. They cost 15. But B-C closes the loop A-B-C, and town E gets nothing. A good rule must take cheap edges and also refuse loops.

Why not test every tree? Count them. In a complete graph, every pair of the n towns has an edge. Call the number of its spanning trees τ, said "tau". Cayley's formula gives it.

Say it aloud

Tau of K-n equals n to the power n minus two.

τ(Kn)
tau of K-n the number of spanning trees of the complete graph on n towns.
n
n the number of towns.
n − 2
to the power n minus two multiply n by itself n − 2 times.
In plain words

Multiply the town count n by itself n − 2 times. The result is how many different spanning trees a brute-force search must price.

With numbers

n = 5: 5 × 5 × 5 = 125 trees. n = 10: 100,000,000. n = 20: about 2.6 × 1023. Our six towns have only ten routes and still 114 spanning trees. The cheapest costs 17.

The failure. Symptom: your network costs more than it should. Measure: count its edges; n or more edges on n towns means a loop. Fix: find the loop and remove its most expensive cable.

The road

  1. The cut property: why the cheapest cable across a split is safe.
  2. The cycle property: which cables no minimum tree uses.
  3. Kruskal: the hero's "Kruskal" button.
  4. Union-find inside Kruskal: how Kruskal spots a loop fast.
  5. Prim: the hero's "Prim" button.
  6. Which one is faster: steps for sparse and dense graphs.
  7. Build your own network: the showcase.
  8. Clustering: cut the longest tree edges.
  9. A tour from a tree, and Borůvka: two more uses.
  10. The field guide: terms, numbers, code and the credit.
A connected graph has 8 towns and 15 edges. How many edges does every spanning tree of it have?

Chapter 1

The Cut Property

Split the towns into two groups, and prove that the cheapest cable across the split is always safe

Greedy rules often fail. Here one fact makes greed safe. Split the towns into two groups, S and the rest. That split is a cut. An edge with one end in each group crosses the cut. The cheapest crossing edge is the light edge.

The cut property (CLRS Theorem 23.1): take the edges you have chosen so far, all inside some MST. Pick a cut that none of them crosses. Then the light edge of that cut is in some MST too. CLRS calls such an edge safe.

Draw a cut

Tap towns to move them to side S (purple). Thick edges cross the cut. The warm one is the light edge.

Illustrative prices. With all ten prices different, every light edge you can find is in the one MST: turn on the MST to check.

Why is it true? Every spanning tree crosses every cut, or the two groups stay apart. Say a minimum tree T crosses only with heavier edges.

Call the light edge (u, v). Adding (u, v) to T closes one loop. The loop crosses the cut twice: once at (u, v) and once at a tree edge (x, y). Remove (x, y) and call the new tree T′. Write w(·) for total weight.

Say it aloud

W of T-prime equals w of T, minus w of x-y, plus w of u-v.

w(T′)
w of T-prime the bill of the new tree, after the swap.
w(T)
w of T the bill of the minimum tree we started from.
w(x, y)
w of x-y the price of the tree edge that also crosses the cut. We take it out.
w(u, v)
w of u-v the price of the light edge. It is no more than w(x, y). We put it in.
In plain words

Start from the bill w(T). Remove the cable (x, y) and add the light cable (u, v). Because w(u, v) is at most w(x, y), the bill w(T′) does not go up. So T′ is also a minimum tree, and it holds the light edge.

With numbers

Cut S = {A, C}. The light edge is A-B, 4. Take a tree T that uses B-C, 5, instead: w(T) = 1 + 2 + 3 + 5 + 7 = 18. The swap gives w(T′) = 18 − 5 + 4 = 17, the true minimum.

This gives CLRS's generic MST method. Every algorithm in this lesson is one version of it.

  1. Start with no edges.
  2. Find a cut that no chosen edge crosses.
  3. Add the light edge of that cut.
  4. Repeat until you have n − 1 edges.

The failure. Symptom: the method adds an edge whose two ends already connect, and a loop appears. Measure: check whether a chosen edge crosses your cut. Fix: use only cuts that no chosen edge crosses. Then the light edge always joins two separate pieces.

No chosen edge crosses a cut. Three edges cross it, with weights 5, 3 and 7. Which edge is safe to add?

Chapter 2

The Cycle Property, and One Tree or Many

Rule out the edges no minimum tree uses, and learn when the answer is unique

The cut property says which edges to take. The cycle property says which to drop. On any loop, an edge heavier than every other edge of that loop is in no MST.

The proof is the same swap, run backwards. Say a tree holds that heaviest edge. Remove it, and the tree splits into two groups: a cut. The loop crosses that cut at least once more, at a lighter edge. Put the lighter edge in. The bill drops, so the first tree was not minimum.

Rule out the heaviest edge on a loop

Pick a loop. Its edges turn teal and its heaviest edge turns red. Turn on the MST to see that red is never in it.

Illustrative prices. The five triangles rule out B-C, C-D, C-F, B-E and E-F: exactly the five edges outside the MST.

Count it on our map. Five triangles rule out five edges. Ten edges minus five leaves five, and those five are the MST. Here the cycle property alone finds the answer.

One tree or many? If all weights differ, the MST is unique. With ties there can be several. Take a triangle with weights 1, 2 and 2: you can drop either 2, so there are two MSTs. Both cost 3. All MSTs of a graph have the same total and the same list of weights.

The MST has one more gift. On the tree route between two towns, the most expensive cable is as cheap as any route allows. B to E in the tree uses B-D 3 and D-E 7, so its worst cable is 7. Every route from B to E has a cable of 7 or more. This is the minimum bottleneck property.

The failure. Symptom: two runs of a correct program return different trees. Measure: compare the totals; equal totals mean ties, not a bug. Fix: break ties by edge index if you need the same tree every time.

A loop has edges of weight 3, 8 and 5, and no other ties. What can you say?

Chapter 3

Kruskal: Cheapest Edge First

Sort every cable, then keep each one that joins two separate pieces

Kruskal's algorithm (1956) looks at edges, not towns:

  1. Sort the edges by weight, cheapest first.
  2. Start with every town as its own piece.
  3. For each edge (u, v) in order: if u and v sit in different pieces, keep the edge and merge the pieces. If not, skip it.
  4. Stop when you have n − 1 edges.

Run Kruskal on the towns

Press Next. Teal is the edge under test. Green edges stay. A red edge would close a loop. The list shows the sorted order.

Illustrative prices. Kruskal stops after its fifth kept edge, so C-F, B-E and E-F are never tested.

Why is every kept edge safe? When Kruskal keeps (u, v), take the cut "u's piece against the rest". No kept edge crosses it. Any cheaper crossing edge came earlier, and Kruskal would have kept it. So (u, v) is the light edge, and the cut property applies. A skipped edge is the heaviest on the loop it would close, so the cycle property drops it.

EdgeWeightActionPieces after
D-F1keep{D,F} {A} {B} {C} {E}
A-C2keep{A,C} {D,F} {B} {E}
B-D3keep{A,C} {B,D,F} {E}
A-B4keep{A,B,C,D,F} {E}
B-C5skip: loop B-A-Cno change
C-D6skip: loop C-A-B-Dno change
D-E7keepone piece; total 17

What does it cost? Call the number of edges E and the number of towns V. Sorting takes about E log₂ E comparisons. Each edge then needs two piece lookups. Chapter 4's union-find makes each lookup cost α(V), a number that is at most 4 in practice.

Say it aloud

T-Kruskal equals big-O of E log E, plus big-O of E times alpha of V.

TKruskal
T-Kruskal the running time of Kruskal.
O(E log E)
big-O of E log E the sort: E edges, about log₂ E comparisons each. Big-O means "grows no faster than, up to a constant".
O(E · α(V))
big-O of E times alpha of V two lookups per edge in union-find. α is the inverse Ackermann function: at most 4 for any V you can store.
In plain words

Sort the E edges once, then do two lookups for each edge. The sort term is larger, so Kruskal runs in O(E log E). That equals O(E log V), because E is less than V² and so log E is less than 2 log V.

With numbers

With made-up sizes: V = 1,000 towns and E = 2,000 cables. The sort takes about 2,000 × 11 = 21,900 comparisons. The lookups take about 2 × 2,000 = 4,000 steps times a small constant.

The failure. Symptom: after all edges, you hold fewer than n − 1. Measure: count the kept edges. Fix: the graph is not connected; report the pieces. What you hold is a minimum spanning forest: one MST per piece.

Kruskal reaches edge (u, v) of weight 5. Find(u) returns 3 and Find(v) returns 3. What happens?

Chapter 4

Union-Find Inside Kruskal

Answer "are these two towns already joined?" in a few pointer steps

Kruskal asks one question per edge: are u and v already in one piece? A fresh search answers it in O(V + E) steps, for every edge. Union-find answers it in a few pointer steps. The full lesson is CLRS 21: Disjoint Sets; here is the part Kruskal needs.

Each piece is a tree of parent pointers. The root names the piece. Find(x) walks up from x to its root. Union(x, y) hangs one root under the other. Two rules keep the trees flat:

  1. Union by rank: hang the root of the shorter tree under the root of the taller tree.
  2. Path compression: after a Find, point every node on the path straight at the root.

Watch Kruskal's lookups

Press Next. The forest shows each piece as a tree; warm rings are roots. Blue marks the path each Find walks. A purple cell is a pointer that just changed.

Union by rank and path compression are both on. On a tie in rank, the root of v goes under the root of u.

Follow the skip of B-C. After A-B, the pointers are B to D and D to A. Find(B) walks 2 hops to A, and compression points B straight at A. Find(C) walks 1 hop to A. Same root, so skip. All seven tests together walk 7 hops.

With both rules, m operations on n elements cost O(m α(n)) in total (CLRS Chapter 21). Kruskal does 2E Finds and V − 1 Unions, so its lookups cost O(E α(V)): the second term of Chapter 3's equation.

The failure. Symptom: Kruskal is slow on a big graph although the sort is fast. Measure: count the pointer hops per Find; a growing count means tall trees. Fix: add both rules.

Why does Kruskal skip B-C in this run?

Chapter 5

Prim: Grow One Tree

Start at one town and always add the cheapest cable that leaves the tree

Kruskal grows many pieces at once. Prim's algorithm grows one tree. Jarník found it in 1930, Prim again in 1957. Start at any town. At each step, add the cheapest edge with one end in the tree and one end outside. That edge is the light edge of the cut "tree against the rest", so the cut property makes it safe.

To find that edge fast, Prim keeps one number per outside town. Call the set of towns already in the tree S. For an outside town v, its key is the price of its cheapest cable into S.

Say it aloud

Key of v equals the minimum, over u in S, of w of u-v.

key[v]
key of v the cheapest way to hook outside town v onto the tree. Infinity if v has no cable into S.
minu ∈ S
the minimum over u in S try every town u already in the tree and keep the smallest value.
w(u, v)
w of u-v the price of the cable from u to v.
In plain words

For town v, look at every cable from v into the tree S. Keep the cheapest price as key[v]. When a new town u joins S, check only its cables. If w(u, v) is less than key[v], lower key[v] to w(u, v).

With numbers

After A and C join, S = {A, C}. A has no cable to D, and C-D costs 6, so key[D] = 6. Then B joins, and B-D costs 3, so key[D] = min(6, 3) = 3.

  1. Set the start town's key to 0 and every other key to infinity.
  2. Take the outside town with the smallest key. It joins the tree by its cheapest cable.
  3. For each neighbour v still outside: if w(u, v) is less than key[v], set key[v] = w(u, v). Remember u as v's parent.
  4. Repeat until every town is in.

Grow Prim's tree

Pick a start and press Next. Purple towns are in the tree. Blue dashed edges leave it; the warm one is the cheapest. The bars are the keys.

Illustrative prices. Both starts end with the same five edges, because all ten prices differ.

TakesKeyJoins byKeys lowered
A0startB ∞ to 4, C ∞ to 2
C2A-CD ∞ to 6, F ∞ to 8
B4A-BD 6 to 3, E ∞ to 9
D3B-DE 9 to 7, F 8 to 1
F1D-Fnone
E7D-Enone; total 17

Prim looks like Dijkstra's shortest-path algorithm (CLRS 24). One line differs. Prim compares w(u, v) with key[v]. Dijkstra compares d[u] + w(u, v), the whole trip from the start, with d[v]. Dijkstra's tree from A costs 19: it reaches E by B-E (9), because the trip A-B-E, 13, beats A-B-D-E, 14.

The failure. Symptom: your "MST" changes when you change the start town, and it costs more than Kruskal's. Measure: compare the totals of both algorithms. Fix: the key update adds up whole trips; make it the price of one cable.

Prim takes town u, which had key 7. Its neighbour v is outside with key[v] = 4, and w(u, v) = 3. What happens?

Chapter 6

Which One Is Faster

Count the steps for sparse and dense graphs, and pick the right tool

A sparse graph has few edges per town, like roads. A dense graph has nearly every pair joined, like the distances between 1,000 points. Both algorithms find the same tree; their costs differ.

Prim with a binary heap (a priority queue that returns the smallest key in log₂ V steps) does V "take the smallest" operations. It also does up to E key decreases, one per edge. Each operation costs about log₂ V.

Say it aloud

T-Prim-heap equals big-O of V plus E, times log V.

TPrim, heap
T-Prim-heap the running time of Prim with a binary heap.
O( )
big-O of grows no faster than, up to a constant.
V
V the number of towns; each leaves the heap once.
E
E the number of edges; each can lower one key once.
log V
log V the height of the heap: the steps one heap operation climbs or falls.
In plain words

Every town leaves the heap once, and every edge may lower one key once. That is V + E heap operations. Each costs log V steps, so multiply.

With numbers

With made-up sizes: V = 1,000 and E = 2,000. (1,000 + 2,000) × 10 ≈ 29,900 steps. Kruskal sorts the same graph in about 21,900. On the complete graph, E = 499,500: the heap needs about 4,990,000 and Kruskal about 9,460,000.

A third version drops the heap. Keep the keys in a plain array and scan all V of them to find the smallest. V scans of V entries cost V² = 1,000,000 for 1,000 towns, whatever E is. On a complete graph that beats both.

Count the steps

Drag the number of towns and pick a density. The axis is logarithmic: each grid line is ten times the last.

1,000

Rough step counts: Kruskal E log₂ E, Prim with a heap (V + E) log₂ V, Prim with an array V². We ignore constants, so treat a gap under 2 times as a tie.

VersionRunning timeBest for
Kruskal + union-findO(E log E)sparse graphs, edges given as a list
Prim + binary heapO((V + E) log V)medium density, adjacency lists
Prim + plain arrayO(V²)complete or near-complete graphs
Prim + Fibonacci heapO(E + V log V)theory: best bound in CLRS 23.2

The failure. Symptom: an MST on 100,000 points runs out of memory. Measure: count the stored edges: 100,000 × 99,999 / 2 is about 5 billion. Fix: use array Prim and compute each distance when you need it; memory stays at O(V).

You need the MST of all pairwise distances between 1,000 points. Which version takes the fewest steps?

Chapter 7

Build Your Own Network

Drag towns, run either algorithm, and watch the same tree appear by two routes

Now the map is yours. A cable can join any pair of towns, and it costs its straight-line length. Drag a town and the tree follows. Then play Kruskal and Prim on the same map and watch the order of their picks.

Drag the towns, run the algorithms

Drag a town. Pick an algorithm and press Play to watch it work. Faint lines are all possible cables.

Illustrative map, 4 to 14 towns. Lengths are in map units. Prim starts at town 1. Teal marks the edge under test.

Four things to try:

  1. Play Kruskal, then Prim. The order differs; the final tree is the same.
  2. Drag one town far from the rest. Its one cable becomes the longest edge in the tree.
  3. Line the towns up in a row. The tree is the row itself.
  4. Watch Kruskal's count of tested edges. It stops long before it has read every edge.

The failure. Symptom: on a perfect square of four towns, Kruskal and Prim draw different trees. Measure: compare totals; both are three sides. Fix: nothing is wrong: equal lengths make ties, and ties allow several MSTs (Chapter 2).

All cable lengths on a map differ. Kruskal and Prim each return a tree. What is true?

Chapter 8

Cut the Longest Edges: Clustering

Delete the k − 1 heaviest tree edges to split points into k groups that sit as far apart as possible

You have points on a map and want k groups. Build the MST. Delete its k − 1 heaviest edges. The pieces that remain are the groups. Statisticians call this single-linkage clustering.

The spacing of a grouping is the distance between the closest two points in different groups. Large spacing means well separated groups. The MST cut gives the largest spacing of any grouping into k groups (Kleinberg and Tardos, Algorithm Design, Section 4.7).

Sort the MST edge weights from heaviest down: d1, d2, and so on. Delete d1 to dk−1, and call the result C*.

Say it aloud

Spacing of C-star equals d sub k minus one.

spacing(C*)
spacing of C-star the gap between the closest two points in different groups of C*.
dk−1
d sub k minus one the (k − 1)-th heaviest MST edge: the lightest of the edges you deleted. k is the number of groups.
In plain words

Delete the k − 1 heaviest tree edges. The last one you delete is dk−1, the lightest of them. No two points in different groups are closer than dk−1.

With numbers

Our six towns: the MST edges weigh 7, 4, 3, 2 and 1. For k = 3, delete 7 and 4. The groups are {E}, {A, C} and {B, D, F}. Spacing = d2 = 4: the cheapest cable between groups is A-B, 4.

Why can no grouping do better? Take any other grouping C into k groups. It must split two points p and q that C* keeps together. The tree path from p to q uses only edges of weight dk−1 or less. Somewhere that path steps from one group of C to another. That step is a cross-group pair at distance dk−1 or less.

Cut the tree into k groups

Drag k. Each step deletes the heaviest remaining tree edge (dashed). Colours mark the groups.

3

Illustrative points: three or four random blobs. The read-out checks the spacing against all pairs by brute force.

The failure. Symptom: one giant group and a few single points. Measure: look at group sizes; a thin line of points can join two blobs, called chaining. Fix: use a method that looks at whole groups, such as average linkage or k-means.

You cluster 100 points into 5 groups with the MST. How many tree edges do you delete?

Chapter 9

A Tour from a Tree, and Borůvka

Turn a tree into a sales tour at most twice the best, and grow every piece at once

A salesman must visit every city once and return home. Finding the shortest such tour is the travelling salesman problem. Nobody knows a fast exact method. Assume the triangle inequality: a direct trip is never longer than a detour. Then the MST gives a tour at most twice the best (CLRS Section 35.2):

  1. Build the MST.
  2. Walk it depth first from one city. List each city the first time you reach it: a preorder walk.
  3. Visit the cities in that order, then return home. Call this tour H.
Say it aloud

W of MST is at most OPT, which is at most w of H, which is at most two times w of MST.

w(MST)
w of MST the total length of the minimum spanning tree.
OPT
opt the length of the best possible tour.
w(H)
w of H the length of the tour H from the preorder walk.
2 · w(MST)
two times w of MST a walk that goes down and back up every tree edge.
In plain words

Remove one edge from the best tour and you get a spanning tree, so w(MST) is at most OPT. Walking down and back each tree edge costs 2 · w(MST). Skipping cities you already saw only shortens that walk, by the triangle inequality, which gives H.

With numbers

Four cities on the corners of a square with side 1. The MST is three sides: 3. The best tour is 4. The preorder walk visits the corners in order and returns: H = 4. So 3 ≤ 4 ≤ 4 ≤ 6.

Turn the tree into a tour

Pick a view. The bars compare the tree, the best tour, the tree tour H and twice the tree on one scale.

7

Illustrative random cities with straight-line distances, which obey the triangle inequality. The device finds the best tour by trying every order, so cities stop at 8.

Borůvka's algorithm (1926) is the oldest MST method. In each round, every piece picks its cheapest outgoing edge, and the round adds them all at once. On our towns, round 1 adds D-F 1, A-C 2, B-D 3 and D-E 7, leaving {A, C} and {B, D, E, F}. Round 2 adds A-B 4. Total 17.

Each round at least halves the number of pieces, so there are at most log₂ V rounds of O(E) work: O(E log V). The pieces choose independently, so a round splits well across many machines.

The failure. Symptom: the tree tour is more than twice the tree. Measure: test the triangle inequality on sample triples of costs. Fix: replace each cost with the shortest-path distance, which obeys it.

The distances obey the triangle inequality and the MST weighs 50. What do you know about the tree tour H?

Chapter 10

The Field Guide

Keep the terms, the numbers, the checks and the core code on one page

A minimum spanning tree joins every vertex for the least total weight, with n − 1 edges and no loop. The cut property makes the cheapest edge across any clean split safe. Kruskal sorts edges and uses union-find; Prim grows one tree with a priority queue. Both cost about O(E log V).

Terms and numbers

TermMeaningNumber on this page
Spanning treereaches every vertex, no loop, n − 1 edges114 trees for our 6 towns; the cheapest costs 17
Cayley's formulaspanning trees of the complete graph: nn−2125 for n = 5
Light edgecheapest edge across a cutA-B, 4, for S = {A, C}
Cut propertya light edge of a clean cut is safeswap: 18 − 5 + 4 = 17
Cycle propertythe strictly heaviest edge of a loop is in no MST5 triangles rule out 5 edges
Kruskalsort, keep an edge when its ends are in different pieces7 tests, 5 keeps, 17
Primgrow one tree; key[v] = cheapest cable into the treeorder A, C, B, D, F, E; 17
Shortest-path treeDijkstra's tree: short trips, not a small bill19 from A
Running timesKruskal O(E log E), Prim heap O((V + E) log V), array O(V²)21,900 / 29,900 / 1,000,000 for V = 1,000, E = 2,000
Spacingclosest pair across groups = dk−14 for k = 3 on our towns
Tree tourw(MST) ≤ OPT ≤ w(H) ≤ 2 · w(MST)3 ≤ 4 ≤ 4 ≤ 6 on a unit square
Borůvkaevery piece adds its cheapest edge each round2 rounds on our towns

Before you trust an MST

  1. Treat edges as two-way. MST is for undirected graphs.
  2. Count the edges: exactly n − 1, or the graph is not connected.
  3. In Kruskal, compare roots, Find(u) == Find(v), never parents.
  4. In Prim, set key[v] to one cable's price, never a running sum.
  5. In lazy Prim, skip heap entries for towns already in the tree.
  6. Expect several valid trees when weights tie; compare totals.

The core code

pythonimport heapq

def kruskal(n, edges):                  # edges: [(w, u, v), ...]
    parent, rank = list(range(n)), [0] * n
    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:
            continue                         # would close a loop
        if rank[ru] < rank[rv]:
            ru, rv = rv, ru                  # union by rank
        parent[rv] = ru
        rank[ru] += rank[ru] == rank[rv]
        tree.append((w, u, v))
        if len(tree) == n - 1:
            break
    return tree

def prim(n, adj, s=0):                   # adj[u]: [(v, w), ...]
    in_tree, tree, pq = [False] * n, [], [(0, s, -1)]
    while pq:
        k, u, p = heapq.heappop(pq)
        if in_tree[u]:
            continue                         # old entry (lazy decrease-key)
        in_tree[u] = True
        if p >= 0:
            tree.append((k, p, u))
        for v, w in adj[u]:
            if not in_tree[v]:
                heapq.heappush(pq, (w, v, u))   # key = one cable, not a sum
    return tree

E = [(4,0,1),(2,0,2),(5,1,2),(3,1,3),(6,2,3),(9,1,4),(7,3,4),(1,3,5),(8,2,5),(10,4,5)]
adj = [[] for _ in range(6)]
for w, u, v in E:
    adj[u].append((v, w)); adj[v].append((u, w))
print(sum(t[0] for t in kruskal(6, E)), sum(t[0] for t in prim(6, adj)))   # 17 17

Where it sits

MST is the standard proof case for greedy algorithms. The cut property is its greedy-choice property, and its proof is the exchange argument of CLRS 16. Faster methods exist. Karger, Klein and Tarjan (1995) find an MST in expected linear time with random sampling. Chazelle (2000) comes within an inverse-Ackermann factor of linear without randomness. Whether a deterministic linear-time method exists is still open.

Keep going

The takeaway. Any cut has a cheapest crossing edge, and that edge is safe. Kruskal and Prim are two ways to pick cuts; everything else is bookkeeping for speed.
Prim's and Dijkstra's code differ in one line. Which?

Now press Present or Teach. Prove the cut property from memory with the swap 18 − 5 + 4 = 17, then trace Kruskal and Prim on the six towns. Then go back to the hero, press Cheapest five, and say which cable breaks it.

Source

T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 23, Minimum Spanning Trees (third edition numbering), with Section 35.2 for the tour. The spacing result follows J. Kleinberg and É. Tardos, Algorithm Design, Section 4.7. The towns, prices, devices and step counts on this page are our own.

CLRS Chapter 23 · Minimum Spanning Trees
Next: Single-Source Shortest Paths · Back to Gleams