Kodewick
开始学 →
最小生成树:Prim 和 Kruskal35 / 52

最小生成树:Prim 和 Kruskal

第 35 课,共 52 课 · 第 6 部分 · 图 · 约 20 分钟

最小生成树用 n − 1 条边连通 n 个顶点,且总权最小:Prim 从一个顶点出发,每次接上最近的顶点;Kruskal 用 sort 把边从短到长排好,用并查集跳过成环的边。

六个村子要通网,任意两个村子之间铺光缆的费用不同。不需要每两个村子都直接相连,只要所有村子连成一片就行。最省钱的方案是什么?连通 n 个村子至少要 n − 1 条线;多一条就有环,环上去掉最贵的那条,照样连通、还更省。所以要找的是:n − 1 条边、把所有顶点连起来、总权最小。这叫最小生成树(MST,minimum spanning tree)。电网、管道、电路板走线,以及聚类算法,都要用到它。

Prim:从一个顶点长出去

Prim 像 Dijkstra:一棵树从一个顶点开始,每次把离这棵树最近的那个顶点接进来,连同那条边。用 lowcost[v] 记「v 到树上任何一个顶点,最短的那条边多长」:

  1. 起点进树,用它的边初始化 lowcost。
  2. 重复 n − 1 次:挑不在树上、lowcost 最小的 v,把它和那条边接进树;再用 v 的边更新别的顶点的 lowcost(变小才改)。

和 Dijkstra 唯一的区别:Dijkstra 比的是 dist[u] + w(到起点的距离),Prim 比的只是 w(到树的距离)。

从 0 开始做 Prim。顶点上的数是 lowcost:它到当前这棵树最短的边;绿色是树上的顶点,粗线是选进树的边

每轮扫一遍 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 开始,边被选进树的先后是?

单选

lowcost 数组写的 Prim 是 O(n²)。它最适合哪种图?

练习 1

写 Prim

补全数组版 Prim 的每一轮:在不在树上的顶点里挑 lowcost 最小的 v,打印 from[v]-v,加上权,标记进树;再用 v 的边更新 lowcost 和 from。

要显示
0-2 2-4 4-3 2-1 3-5 
18
exercise1.cpp
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}
输出
点「运行」或按 Ctrl+Enter

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)。

Kruskal:边从短到长一条条看。一开始每个顶点自成一块,选一条边就把两块并成一块

排序 O(e log e),后面看每条边是否连通几乎是 O(1)(靠下一关的并查集),所以 Kruskal 是 O(e log e),适合稀疏图。

如果不判环,只拿最短的 n − 1 条边,会怎样?

main.cpp
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)。

012345parent012345sz111111

Kruskal 一路做下来,parent 和 sz 的变化。sz 只有根的那一格有意义;一样大时,把第二个根挂到第一个下面

写成一个类,parent 和 sz 是它的成员。边用 struct Edge,排序用 sort 加一个 lambda:

main.cpp
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}
练习 2

并查集数块

补全 DSU 的 find(带路径压缩)和 unite(按大小合并:小的根挂到大的根下面,sz 加上去)。程序做完几次 unite 以后,数一数有几个根(parent[i] == i),再看 0 所在的块有几个顶点。

要显示
3 块;0 和 2 连通;0 所在的块有 4 个
exercise2.cpp
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}
输出
点「运行」或按 Ctrl+Enter

用 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 的堆写法一样,堆里放 (边权, 顶点),弹出来已经在树上的就跳过。
main.cpp
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) { … }) 给边排序。花括号里该写哪一句?

Prim 还是 Kruskal

两种算法都能求出最小生成树,考试和面试常问「什么时候用哪个」和几个容易混的结论。

PrimKruskal
怎么长一棵树从一个顶点长大很多块,一边选一边合并
每步接上离树最近的顶点下一条最短的边,不成环就选
要用lowcost 数组,或 priority_queuesort + 并查集
时间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];