The problem
Five places and seven possible cables, each with a cost: its weight. A spanning tree joins every vertex using V − 1 = 4 edges and no cycle. The minimum spanning tree (MST) is the one with the smallest total weight.
Growing the tree
Prim grows a single tree from a start vertex, here A. A priority queue (a min-heap) holds offers (weight, from, to) and always hands out the smallest. It starts with (0, A, A): reach A for free.
Pop (0, A, A). A is not in seen, so it joins the tree. Then every edge from A to a vertex outside the tree becomes an offer: (4, A, B) and (1, A, C) go into the queue.
The smallest offer is (1, A, C). C is new, so edge A–C joins the tree: weight 1. C then offers its edges to B, D and E. Edges back to A are not offered: A is already in.
Next comes (2, C, B), cheaper than the older (4, A, B). B joins by edge C–B, and the total is 3. B offers its edge to D, (5, B, D). The offer (4, A, B) is still waiting in the queue.
Out comes (4, A, B). Both A and B are already in the tree, so taking A–B would close the cycle A, C, B. Line 5 skips it. Leaving old offers in the queue and skipping them later is the lazy version of Prim.
The smallest offer is now (5, B, D), so D joins by edge B–D and the total is 8. D offers (3, D, E). E already had an offer of 6 through C, but the new one is cheaper.
Pop (3, D, E): E joins by edge D–E and the total is 11. Notice that 3 came after 5. Prim takes the cheapest edge leaving the tree it has so far, not the cheapest edge in the whole graph.
The last offers, (6, C, E) and (7, C, D), are both stale and skipped. The queue is empty, so the loop ends. The tree has 4 edges and total weight 11: the minimum spanning tree.
Proof and cost
Go back to the tree {A, C}. Split the vertices into the tree and the rest: a cut. Its crossing edges cost 2, 4, 6 and 7. Any spanning tree must cross it; swapping in the cheapest crossing edge never costs more.
Each edge is pushed at most once, so the queue holds at most E + 1 offers. Here: 8 pushes, 8 pops, 3 stale. Each heap operation costs O(log E), so the total is O(E log E) = O(E log V).
What happens
;; step 1/11 · the-problem an undirected weighted graph, V = 5 vertices, E = 7 edges A – B weight 4 A – C weight 1 B – C weight 2 B – D weight 5 C – D weight 7 C – E weight 6 D – E weight 3 spanning tree: V − 1 edges, reaches every vertex, no cycle all weights differ, so exactly one MST exists
The figure lines the queue up smallest first so it is easy to read. Python’s heapq really keeps the list in heap order, where only pq[0] is guaranteed to be the smallest; heappop hands out the same offers in the same order. This is lazy Prim: stale offers stay in the queue (Sedgewick and Wayne: space proportional to E, time proportional to E log E). The eager version keeps one offer per vertex in an indexed queue and lowers it with decrease-key: space V, time E log V. CLRS and MIT 6.046J use that version.