最小生成树模板
作者:互联网
#include <bits/stdc++.h>
using namespace std;
const int maxn=500001;
int fa[maxn],n,m,ans,s;
struct edge{
int x,y,z;
}a[500001];
bool cmp(edge x,edge y){
return x.z<y.z;
}
int find(int x){
if(fa[x]==x)
return x;
return fa[x]=find(fa[x]);
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].z);
sort(a+1,a+m+1,cmp);
for(int i=1;i<=n;i++)
fa[i]=i;
for(int i=1;i<=m;i++)
if(find(a[i].x)!=find(a[i].y)){
fa[find(a[i].y)]=find(a[i].x);
ans+=a[i].z;
s++;
if(s>=n-1)
break;
}
printf("%d",ans);
return 0;
}
标签:return,int,最小,生成,edge,maxn,ans,500001,模板 来源: https://blog.csdn.net/qq_42875611/article/details/88141109