Minimum spanning trees with Prim
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Join every vertex of a weighted graph as cheaply as possible. Prim's algorithm grows one tree from a start vertex and always adds the cheapest edge leaving it. Watch offers flow from the edges into a min-heap and come out smallest first on a 5-vertex, 7-edge graph, skip the stale ones that would close a cycle, and finish with a tree of weight 11. Then prove the greedy choice is safe with the cut property and count the cost. It uses the heaps from "Binary heaps: sift up and sift down" and "Priority queues and heapsort", and the exchange argument from "Greedy choices: the exchange argument and when greedy fails". "Minimum spanning trees with Kruskal" solves the same problem a different way.
The cheapest network
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.
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 cheapest network
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.
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 existsOne tree, one queue
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.
seen = set of vertices in the tree start push (0, A, A) tree none weight 0 seen {} queue (0, A, A) heappop always returns the smallest tupleA joins, offers its edges
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.
pop (0, A, A) A joins the tree (no edge) push (4, A, B) push (1, A, C) tree none weight 0 seen {A} queue (1, A, C) (4, A, B)Take the cheapest edge out
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.
pop (1, A, C) C joins, edge A–C (1) push (2, C, B) push (7, C, D) push (6, C, E) tree A–C weight 1 seen {A, C} queue (2, C, B) (4, A, B) (6, C, E) (7, C, D)B joins through C
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.
pop (2, C, B) B joins, edge C–B (2) push (5, B, D) tree A–C B–C weight 3 seen {A, C, B} queue (4, A, B) (5, B, D) (6, C, E) (7, C, D)Skip an offer that loops
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.
pop (4, A, B) B is already in the tree: skip tree A–C B–C weight 3 seen {A, C, B} queue (5, B, D) (6, C, E) (7, C, D) a stale offer: both ends are already in seenD joins for 5
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 (5, B, D) D joins, edge B–D (5) push (3, D, E) tree A–C B–C B–D weight 8 seen {A, C, B, D} queue (3, D, E) (6, C, E) (7, C, D)E joins for 3, not 6
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.
pop (3, D, E) E joins, edge D–E (3) tree A–C B–C B–D D–E weight 11 seen {A, C, B, D, E} queue (6, C, E) (7, C, D) edges taken in the order 1, 2, 5, 3Empty queue: the MST
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.
pop (6, C, E) E is already in the tree: skip pop (7, C, D) D is already in the tree: skip tree A–C B–C B–D D–E weight 11 seen {A, C, B, D, E} queue empty tree = [('A', 'C', 1), ('C', 'B', 2), ('B', 'D', 5), ('D', 'E', 3)] sum of weights = 11Why the cheapest is safe
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.
cut property: the cheapest edge crossing a cut is in the MST tree side {A, C}, other side {B, D, E} crossing: C–B 2, A–B 4, C–E 6, C–D 7 (the queue holds exactly these) proof by exchange (the greedy argument): suppose an MST T leaves out C–B T + C–B has a cycle, which crosses the cut a second time at some e′ T − e′ + C–B is a spanning tree that weighs less, since 2 < w(e′) contradiction, so C–B is in every MSTHow much it costs
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).
this run: V = 5, E = 7 pushes 8 (the start + one per edge) pops 8 (5 join, 3 stale) E ≤ V², so log E ≤ 2 log V: O(E log E) = O(E log V) lazy (this code): space O(E) eager, indexed heap: space O(V) Fibonacci heap: O(E + V log V) (CLRS, MIT 6.046J)
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Starting from A, in what order does Prim add the tree edges in this lesson's graph?
Prim takes the cheapest edge leaving the tree it has so far. D–E (3) only becomes an offer once D is in, and D joins by B–D (5). So the order is 1, 2, 5, 3, total 11.
02The offer (4, A, B) comes out of the queue after A, C and B are already in the tree. What does the code do?
Both ends are already in the tree, so A–B would close the cycle A, C, B. Line 5 (if v in seen: continue) skips the stale offer.
03What does the cut property say?
With distinct weights, the cheapest crossing edge of any cut is in the MST. Prim uses the cut 'tree versus the rest' at every step, so each edge it adds is safe.
04Why is O(E log E) the same as O(E log V) for Prim?
A simple graph has at most V(V − 1)/2 edges, which is less than V². Taking logs, log E < 2 log V, and the constant 2 disappears inside O.
05How does Prim differ from Kruskal?
Both are greedy and both find a minimum spanning tree. Prim keeps one growing tree; Kruskal sorts all edges and merges many small trees with union-find.
المسرد
- Weighted graph
- A graph where every edge carries a number, its weight, such as a cost or a length.
- Spanning tree
- A set of V − 1 edges that reaches every vertex of a connected graph and contains no cycle.
- Minimum spanning tree (MST)
- A spanning tree whose edge weights add up to the smallest possible total.
- Cut
- A split of the vertices into two groups. An edge crosses the cut if its ends are in different groups.
- Cut property
- With distinct weights, the cheapest edge crossing any cut belongs to the MST.
- Min-heap
- A priority queue that always hands out its smallest item first. Python's heapq module provides one on a plain list.
- Stale offer
- An edge still in the queue whose far end has already joined the tree. Taking it would close a cycle, so it is skipped.
- Lazy Prim
- The version of Prim that leaves stale offers in the queue and skips them when they come out, instead of updating them.
الملاحظات والمصادر
- 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.
- Every weight in the example is different, so the MST is unique and the cut proof can use a strict “less than”. With equal weights there may be several MSTs of the same total, and Prim returns one of them.
- Prim needs a connected graph. On a graph in several pieces it returns a spanning tree of the start vertex’s piece only.
- The code is real Python 3. With the graph above it prints [('A', 'C', 1), ('C', 'B', 2), ('B', 'D', 5), ('D', 'E', 3)] and then 11.
- Sedgewick and Wayne, Algorithms 4th ed., §4.3 Minimum Spanning Trees
- MIT 6.046J Design and Analysis of Algorithms (Spring 2015), Lecture 12: Greedy Algorithms: Minimum Spanning Tree
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 8: Binary Heaps
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 21: Minimum Spanning Trees
- Python documentation: heapq, Heap queue algorithm
اختبار يتاح بعد الخطوة الأخيرة.