#问题
假设G=(V,E)是一个连通网,U是顶点V的一个非空子集。若(u,v)是一条具有最小权值的边,其中u∈U,v∈V-U,则必存在一棵包含边(u,v)的最小生成树。
#解析
选择无向图中最小权值的边的两端顶点,放进集合U,寻找下一条权值最小的边,将边的顶点加入集合U并且不形成回路
#代码
#include <bits/stdc++.h>
using namespace std;
const int maxm = 2e5+1;
const int INF = 0x7fffffff/2;
struct edge{
int from, to, cost;
};
edge es[maxm]; // 存边
int n, m, ans, fa[maxm], rk[maxm];
bool cmp(const edge &x, const edge &y){
return x.cost<y.cost;
}
int find(int x){
return fa[x]==x ? x : fa[x] = find(fa[x]);
}
void kruskal(){
sort(es+1, es+m+1, cmp);
for(int i=1; i<=n; i++){
fa[i] = i;
rk[i] = 1;
}
int cnt = 1, ans = 0; // cnt是生成树中的顶点数,ans是最短权之和
for(int i=1; i<=m; i++){
edge e = es[i];
int fx = find(e.from);
int fy = find(e.to);
if(fx!=fy){
if(rk[fx]<rk[fy])
fa[fx] = fy;
else{
fa[fy] = fx;
if(rk[fx]==rk[fy])
rk[fx]++;
}
ans += e.cost;
cnt++;
if(cnt>=n) // 找够了n个顶点
break;
}
}
if(cnt>=n)
printf("%d", ans);
else // 无法找到n个顶点,说明不连通
printf("orz");
}
void rd(){
scanf("%d %d", &n, &m);
for(int i=1; i<=m; i++)
scanf("%d %d %d", &es[i].from, &es[i].to, &es[i].cost);
}
int main(){
rd();
kruskal();
return 0;
}