【图论】KruskalMST算法
适用于无向图。其实找出来的是一片最小生成森林来的,并不一定是树,取决于原图是否连通。
int n, m;
const int MAXM = 200000 + 10;
struct DisjointSet {
static const int MAXN = 200000 + 10;
int fnd[MAXN], siz[MAXN];
void Init(int n) {
for(int i = 1; i <= n; i++)
fnd[i] = i, siz[i] = 1;
}
int Find(int x) {
return x == fnd[x] ? x : fnd[x] = Find(fnd[x]);
}
bool Merge(int x, int y) {
x = Find(x), y = Find(y);
if(x == y)
return 0;
if(siz[x] < siz[y])
swap(x, y);
fnd[y] = x;
siz[x] += siz[y];
return 1;
}
} dsu;
struct Edge {
int u, v, w;
bool operator<(const Edge& edge)const {
return w < edge.w;
}
} edge[MAXM];
ll mst() {
for(int i = 1; i <= m; ++i)
edge[i] = {u, v, w};
sort(edge + 1, edge + 1 + m);
dsu.Init(n);
ll res = 0;
for(int i = 1; i <= m; ++i) {
int u = edge[i].u;
int v = edge[i].v;
int w = edge[i].w;
if(dsu.Merge(u, v))
res += w;
}
return res;
}