最小生成樹:Prim 和 Kruskal
最小生成樹用 n − 1 條邊連通 n 個頂點,且總權最小:Prim 從一個頂點出發,每次接上最近的頂點;Kruskal 用 sort 把邊從短到長排好,用並查集跳過成環的邊。
六個村子要通網,任意兩個村子之間鋪光纜的費用不同。不需要每兩個村子都直接相連,只要所有村子連成一片就行。最省錢的方案是什麼?連通 n 個村子至少要 n − 1 條線;多一條就有環,環上去掉最貴的那條,照樣連通、還更省。所以要找的是:n − 1 條邊、把所有頂點連起來、總權最小。這叫最小生成樹(MST,minimum spanning tree)。電網、管道、電路板走線,以及聚類演算法,都要用到它。
Prim:從一個頂點長出去
Prim 像 Dijkstra:一棵樹從一個頂點開始,每次把離這棵樹最近的那個頂點接進來,連同那條邊。用 lowcost[v] 記「v 到樹上任何一個頂點,最短的那條邊多長」:
- 起點進樹,用它的邊初始化 lowcost。
- 重複 n − 1 次:挑不在樹上、lowcost 最小的 v,把它和那條邊接進樹;再用 v 的邊更新別的頂點的 lowcost(變小才改)。
和 Dijkstra 唯一的區別:Dijkstra 比的是 dist[u] + w(到起點的距離),Prim 比的只是 w(到樹的距離)。
每輪掃一遍 lowcost 找最小、再掃一遍更新,n 輪:O(n²),和邊數無關。所以陣列版的 Prim 適合稠密圖。程式碼留到練習裡自己寫,它和上一課 Dijkstra 的陣列版幾乎一樣。
邊 A–B 3、A–C 1、B–C 2、B–D 4、C–D 5、D–E 2、C–E 6。用 Prim 從 A 開始,邊被選進樹的先後是?
A–C B–C D–E B–D 是 Kruskal 的順序:D–E 雖然只有 2,可一開始它兩頭都不在樹上,Prim 夠不著它。lowcost 陣列寫的 Prim 是 O(n²)。它最適合哪種圖?
寫 Prim
✓補全陣列版 Prim 的每一輪:在不在樹上的頂點裡挑 lowcost 最小的 v,印出 from[v]-v,加上權,標記進樹;再用 v 的邊更新 lowcost 和 from。
0-2 2-4 4-3 2-1 3-5 18
1#include <iostream>2#include <vector>3using namespace std;4 5const int INF = 1000000000;6 7int main() {8 int n = 6;9 vector<vector<int>> w(n, vector<int>(n, INF));10 auto add = [&](int u, int v, int c) { w[u][v] = w[v][u] = c; };11 add(0, 1, 6); add(0, 2, 1); add(1, 2, 4); add(1, 3, 5); add(2, 3, 7);12 add(2, 4, 3); add(3, 4, 2); add(3, 5, 8); add(4, 5, 9);13 vector<bool> in(n, false);14 vector<int> lowcost(w[0]), from(n, 0); // lowcost 一開始是 0 的那一行15 int total = 0;16 in[0] = true;17 for (int k = 1; k < n; k++) {18 int v = -1;19 // 1. 不在樹上的裡找 lowcost 最小的 v20 // 2. 印出 from[v]-v,total 加上 lowcost[v],in[v] = true21 // 3. 對每個不在樹上的 j:w[v][j] < lowcost[j] 就更新 lowcost[j] 和 from[j]22 }23 cout << "\n" << total << "\n";24 return 0;25}
Kruskal:邊從短到長,不成環就選
Kruskal 換個角度:不管樹長在哪,把所有邊按權從小到大排好,一條條看:這條邊的兩頭還不連通,就選它;已經連通了,選它就會成環,跳過。選夠 n − 1 條就停。
排好的邊:0–2 (1)、3–4 (2)、2–4 (3)、1–2 (4)、1–3 (5)、0–1 (6)、2–3 (7)、3–5 (8)、4–5 (9)。
排序 O(e log e),後面看每條邊是否連通幾乎是 O(1)(靠下一關的並查集),所以 Kruskal 是 O(e log e),適合稀疏圖。
如果不判環,只拿最短的 n − 1 條邊,會怎樣?
1#include <iostream>2#include <vector>3using namespace std;4 5struct Edge { int u, v, w; };6 7int main() {8 // 已經按權排好序的 9 條邊9 vector<Edge> e = {{0, 2, 1}, {3, 4, 2}, {2, 4, 3}, {1, 2, 4}, {1, 3, 5},10 {0, 1, 6}, {2, 3, 7}, {3, 5, 8}, {4, 5, 9}};11 int total = 0;12 bool touches5 = false;13 for (int i = 0; i < 5; i++) { // 直接拿最短的 5 條14 cout << e[i].u << "-" << e[i].v << "(" << e[i].w << ") ";15 total += e[i].w;16 if (e[i].u == 5 || e[i].v == 5) touches5 = true;17 }18 cout << "\n總權 " << total << ",比 18 還小\n";19 cout << "頂點 5 連上了嗎:" << (touches5 ? "連上了" : "沒有") << "\n";20 return 0;21}
0-2(1) 3-4(2) 2-4(3) 1-2(4) 1-3(5) 總權 15,比 18 還小 頂點 5 連上了嗎:沒有
總權 15 看起來更省,可 1–2、2–4、3–4、1–3 圍成了一個環,5 條邊裡有一條白花了,頂點 5 也沒連上。每條邊都要先問一句「兩頭連通了嗎」。
同一個圖:邊 A–B 3、A–C 1、B–C 2、B–D 4、C–D 5、D–E 2、C–E 6。Kruskal 選中邊的先後是?
還是這個圖,Kruskal 第一條被跳過的邊是哪條?
並查集:兩個頂點連通了嗎
Kruskal 要反覆問「u 和 v 在不在同一塊」,還要「把兩塊並起來」。並查集(union-find,也叫 DSU)專門幹這個:每塊是一棵樹,用 vector<int> parent 存,每個頂點指向它的父親,根指向自己。
find(x):順著 parent 一直走到根。兩個頂點的根相同,就在同一塊。unite(a, b):找到兩個根,把一個根掛到另一個下面。
樹可能越掛越高,find 要走很遠。兩個辦法一起用:
- 路徑壓縮:find 走到根以後,把路上經過的每個頂點都直接指向根,下次一步就到。
- 按大小合併:再開一個
sz,記每塊有幾個頂點;合併時小的掛到大的下面,樹就不會長歪。
兩個都用上,每次操作平均幾乎是常數(嚴格說是 O(α(n)),α 是一個長得極慢的函式,n 是宇宙裡原子的個數時也不超過 5)。
寫成一個類,parent 和 sz 是它的成員。邊用 struct Edge,排序用 sort 加一個 lambda:
1#include <iostream>2#include <vector>3#include <algorithm>4#include <numeric>5using namespace std;6 7struct Edge { int u, v, w; };8 9class DSU {10public:11 vector<int> parent, sz;12 DSU(int n) : parent(n), sz(n, 1) {13 iota(parent.begin(), parent.end(), 0); // parent[i] = i14 }15 int find(int x) { // 找根,順便把路上的都直接指向根16 if (parent[x] != x)17 parent[x] = find(parent[x]);18 return parent[x];19 }20 bool unite(int a, int b) { // 已經連通返回 false21 a = find(a);22 b = find(b);23 if (a == b) return false;24 if (sz[a] < sz[b]) swap(a, b); // 小的掛到大的下面25 parent[b] = a;26 sz[a] += sz[b];27 return true;28 }29};30 31int main() {32 int n = 6;33 vector<Edge> e = {{0, 1, 6}, {0, 2, 1}, {1, 2, 4}, {1, 3, 5}, {2, 3, 7},34 {2, 4, 3}, {3, 4, 2}, {3, 5, 8}, {4, 5, 9}};35 sort(e.begin(), e.end(), [](const Edge& a, const Edge& b) { return a.w < b.w; });36 DSU d(n);37 int picked = 0, total = 0;38 for (const Edge& x : e) {39 if (picked == n - 1) break;40 if (!d.unite(x.u, x.v)) {41 cout << "跳過 " << x.u << "-" << x.v << "(" << x.w << "):會成環\n";42 continue;43 }44 picked++;45 total += x.w;46 cout << "選 " << x.u << "-" << x.v << "(" << x.w << ")\n";47 }48 cout << "總權 " << total << "\nparent:";49 for (int p : d.parent) cout << p << " ";50 d.find(4);51 cout << "\nfind(4) 以後:";52 for (int p : d.parent) cout << p << " ";53 cout << "\n";54 return 0;55}
選 0-2(1) 選 3-4(2) 選 2-4(3) 選 1-2(4) 跳過 1-3(5):會成環 跳過 0-1(6):會成環 跳過 2-3(7):會成環 選 3-5(8) 總權 18 parent:0 0 0 0 3 0 find(4) 以後:0 0 0 0 0 0
邊 1–3 (5)、0–2 (3)、0–1 (1)、2–3 (4)、1–2 (2),最小生成樹的總權是多少?
1#include <iostream>2#include <vector>3#include <algorithm>4#include <numeric>5using namespace std;6 7struct Edge { int u, v, w; };8 9class DSU {10public:11 vector<int> parent, sz;12 DSU(int n) : parent(n), sz(n, 1) { iota(parent.begin(), parent.end(), 0); }13 int find(int x) {14 if (parent[x] != x) parent[x] = find(parent[x]);15 return parent[x];16 }17 bool unite(int a, int b) {18 a = find(a);19 b = find(b);20 if (a == b) return false;21 if (sz[a] < sz[b]) swap(a, b);22 parent[b] = a;23 sz[a] += sz[b];24 return true;25 }26};27 28int main() {29 vector<Edge> e = {{1, 3, 5}, {0, 2, 3}, {0, 1, 1}, {2, 3, 4}, {1, 2, 2}};30 sort(e.begin(), e.end(), [](const Edge& a, const Edge& b) { return a.w < b.w; });31 DSU d(4);32 int total = 0;33 for (const Edge& x : e)34 if (d.unite(x.u, x.v)) total += x.w;35 cout << total << "\n";36 return 0;37}
6 個頂點一開始各自是根(parent[i] = i)。依次做 union(0, 1)、union(2, 3)、union(1, 3),union(a, b) 是 parent[find(a)] = find(b)。parent 陣列變成什麼?
Kruskal 遇到兩頭已經連通的邊,該怎麼辦?選一個填進去,讓程式印出最小生成樹的總權 18。
1#include <iostream>2#include <vector>3#include <algorithm>4#include <numeric>5using namespace std;6 7struct Edge { int u, v, w; };8 9vector<int> parent(6);10 11int find(int x) {12 if (parent[x] != x) parent[x] = find(parent[x]);13 return parent[x];14}15 16int main() {17 vector<Edge> e = {{0, 1, 6}, {0, 2, 1}, {1, 2, 4}, {1, 3, 5}, {2, 3, 7},18 {2, 4, 3}, {3, 4, 2}, {3, 5, 8}, {4, 5, 9}};19 sort(e.begin(), e.end(), [](const Edge& a, const Edge& b) { return a.w < b.w; });20 iota(parent.begin(), parent.end(), 0);21 int total = 0;22 for (const Edge& x : e) {23 int a = find(x.u), b = find(x.v);24 if (a == b) ;25 parent[a] = b;26 total += x.w;27 }28 cout << total << "\n";29 return 0;30}
continue。寫成 break,在 1–3 這條第一次成環的邊就停了,5 沒連上,總權只有 10。並查集數塊
✓補全 DSU 的 find(帶路徑壓縮)和 unite(按大小合併:小的根掛到大的根下面,sz 加上去)。程式做完幾次 unite 以後,數一數有幾個根(parent[i] == i),再看 0 所在的塊有幾個頂點。
3 塊;0 和 2 連通;0 所在的塊有 4 個
1#include <iostream>2#include <vector>3#include <numeric>4#include <algorithm>5using namespace std;6 7class DSU {8public:9 vector<int> parent, sz;10 DSU(int n) : parent(n), sz(n, 1) { iota(parent.begin(), parent.end(), 0); }11 int find(int x) {12 // parent[x] 不是自己,就 parent[x] = find(parent[x]);最後返回 parent[x]13 return x;14 }15 void unite(int a, int b) {16 // a、b 換成各自的根;相同就返回;sz 小的那個根掛到大的下面,sz 加上去17 }18 int size(int x) { return sz[find(x)]; }19};20 21int main() {22 DSU d(8);23 d.unite(0, 1); d.unite(2, 3); d.unite(1, 3); d.unite(5, 6); d.unite(6, 7);24 int blocks = 0;25 for (int i = 0; i < 8; i++)26 if (d.parent[i] == i) blocks++;27 cout << blocks << " 塊;0 和 2 " << (d.find(0) == d.find(2) ? "連通" : "不連通");28 cout << ";0 所在的塊有 " << d.size(0) << " 個\n";29 return 0;30}
用 STL 寫
STL 裡沒有並查集,也沒有最小生成樹,上一關那個 20 行的 DSU 類就是大家手寫的樣子。用得上的是兩樣:
sort加比較函式:Kruskal 的邊排序。sort是 introsort(快排為主,太深了換堆排序,小段用插入排序),O(e log e)。lambda[](const Edge& a, const Edge& b) { return a.w < b.w; }必須是「嚴格小於」,寫成<=是未定義行為。priority_queue:Prim 的「找離樹最近的」換成小頂堆,和上一課 Dijkstra 的堆寫法一樣,堆裡放(邊權, 頂點),彈出來已經在樹上的就跳過。
1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5#include <utility>6using namespace std;7 8const int INF = 1000000000;9typedef pair<int, int> P;10 11int main() {12 int n = 6;13 vector<vector<P>> g(n); // g[u] 裡是 (v, w)14 auto add = [&](int u, int v, int w) {15 g[u].push_back({v, w});16 g[v].push_back({u, w});17 };18 add(0, 1, 6); add(0, 2, 1); add(1, 2, 4); add(1, 3, 5); add(2, 3, 7);19 add(2, 4, 3); add(3, 4, 2); add(3, 5, 8); add(4, 5, 9);20 21 vector<int> lowcost(n, INF), from(n, -1);22 vector<bool> in(n, false);23 priority_queue<P, vector<P>, greater<P>> pq; // (到樹的邊權, 頂點)24 lowcost[0] = 0;25 pq.push({0, 0});26 int total = 0, pops = 0;27 while (!pq.empty()) {28 int w = pq.top().first, v = pq.top().second;29 pq.pop();30 pops++;31 if (in[v]) continue; // 已經在樹上:過期的32 in[v] = true;33 total += w;34 if (from[v] != -1) cout << from[v] << "-" << v << " ";35 for (const P& e : g[v])36 if (!in[e.first] && e.second < lowcost[e.first]) {37 lowcost[e.first] = e.second;38 from[e.first] = v;39 pq.push({e.second, e.first});40 }41 }42 cout << "\n總權 " << total << ",彈出 " << pops << " 次\n";43 return 0;44}
0-2 2-4 4-3 2-1 3-5 總權 18,彈出 9 次
選邊的順序和陣列版一樣。每條邊最多進堆一次,O(e log e) = O(e log n):稀疏圖上比 O(n²) 快,稠密圖(e 接近 n²)上反而是陣列版快。
Kruskal 用 sort(e.begin(), e.end(), [](const Edge& a, const Edge& b) { … }) 給邊排序。花括號裡該寫哪一句?
<。<= 讓 comp(x, x) 成立,是未定義行為;a.w - b.w 是 C 的 qsort 的寫法,在這裡會被當成 bool,只要不相等就是 true,排出來是亂的;> 把邊從長到短排,選出來的是總權最大的生成樹。Prim 還是 Kruskal
兩種演算法都能求出最小生成樹,考試和麵試常問「什麼時候用哪個」和幾個容易混的結論。
| Prim | Kruskal | |
|---|---|---|
| 怎麼長 | 一棵樹從一個頂點長大 | 很多塊,一邊選一邊合併 |
| 每步 | 接上離樹最近的頂點 | 下一條最短的邊,不成環就選 |
| 要用 | lowcost 陣列,或 priority_queue | sort + 並查集 |
| 時間 | O(n²);堆 O(e log n) | O(e log e) |
| 適合 | 稠密圖 | 稀疏圖 |
邊權各不相同時,最小生成樹是唯一的,兩種演算法選出同一組邊;有相同的邊權時,可能有好幾棵,但總權一樣。
面試裡: 「連線所有點的最小費用」「最低成本聯通所有城市」就是最小生成樹,Kruskal 最好寫:sort 邊,再一個並查集。並查集本身也常單獨考:「省份數量」「冗餘連線」「賬戶合併」,要能當場寫出帶路徑壓縮和按大小合併的 find / unite。408 常考「寫出 Prim(從某個頂點開始)/ Kruskal 選邊的順序」,以及「最小生成樹中兩點之間的路徑是最短路嗎」(不是,那是 Dijkstra 的事)。
一個連通圖的邊權各不相同。它的最小生成樹有幾棵?
三角形 A–B 2、B–C 2、A–C 3 的最小生成樹是 A–B 和 B–C。樹上 A 到 C 的路徑長 4,圖裡 A 到 C 的最短路是多少?
小結
最小生成樹:n − 1 條邊,連通,總權最小
- Prim:從一個頂點長,每次接上離樹最近的;陣列 O(n²) 適合稠密圖,priority_queue 版 O(e log n)
- Kruskal:sort 邊從短到長,兩頭不連通才選;O(e log e),稀疏圖
- 並查集:find 找根並路徑壓縮,unite 把小的根掛到大的下面
- 不判環會選出環、漏掉頂點
1int find(int x) {2 if (parent[x] != x) parent[x] = find(parent[x]);3 return parent[x];4}5a = find(a); b = find(b); if (a == b) return false;6if (sz[a] < sz[b]) swap(a, b); parent[b] = a; sz[a] += sz[b];