【模板】Kruskal重构树
备注相关试题:1.货车运输
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 2;
const int M = 1e6 + 2;
int n, m, wcnt;
int son[N << 1][2], fa[N << 1];
int val[N << 1];
struct Edge {
int u, v, w;
} e[M];
int fifa(int x) {
return (fa[x] == x) ? x : fa[x] = fifa(fa[x]);
}
void Build() {
int sum = 0, wcnt = n;
for (int i = 1; i <= m; i++) {
int u = e[i].u, v = e[i].v, w = e[i].w;
int fau = fifa(fa[u]);
int fav = fifa(fa[v]);
if (fau == fav) continue;
fa[fau] = fa[fav] = ++wcnt;
fa[wcnt] = wcnt;
son[wcnt][0] = fau;
son[wcnt][1] = fav;
val[wcnt] = w;
sum++;
if (sum == n - 1) break;
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) fa[i] = i;
int u, v, w;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &u, &v, &w);
e[i].u = u;
e[i].v = v;
e[i].w = w;
}
sort(e + 1, e + 1 + m, [](Edge x, Edge y) {
return x.w > y.w;
});
Build();
return 0;
}