#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=10010;
int f[maxn],rank[maxn];
struct node{
int x,y,w;
}a[maxn];
bool cmp(node x,node y){
return x.w<y.w;
}
int fa(int x){
if(f[x]!=x)
x=fa(f[x]);
return f[x];
}//find his father
int find(int x,int y){
if(fa(x)==fa(y))return 0;
return 1;
} //do they have mutual father ?
void link(int x,int y){
if(rank[x]>=rank[y]){
f[fa(y)]=fa(x);
rank[fa(y)]++;
}
else{
f[fa(x)]=fa(y);
rank[fa(x)]++;
}
}// let's merge!
int main(){
int i,j,k,m,n;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
f[i]=i;//everyone is his own father;
for(i=1;i<=m;i++)
scanf("%d%d%d",&a[i].x,&a[i].y ,&a[i].w );
sort(a+1,a+n+1,cmp);
s=n-1;
i=0;
int ans=0;
while(s && i<=m){
i++;
if(find(a[i].x,a[i].y)){
link(a[i].x,a[i].y);
s--;
ans+=a[i].w;
}
}
printf("罗旅洲 %d",ans);
return 0;
}
code by 罗旅洲
最小生成树+并查集+ kruskal
最新推荐文章于 2022-07-05 01:08:50 发布