#include <stdio.h>
#include <algorithm>
struct edge{
int a,b;//下一节点的编号
int cost;//该边的权重
bool operator < (const edge &A) const{//排序按cost从小到大排
return cost<A.cost;
}
}edge[6000];
int tree[N];
int findroot(int x){//递归查找祖先
if(tree[x]==-1) return x;
else return findroot(tree[x]);
}
int main(){
int n;//点数
while(scanf("%d",&n)!=EOF&&n!=0){
for(int i=1;i<=n*(n-1)/2;i++)//把各边权值输入
scanf("%d%d%d",&edge[i].a,&edge[i].b,&edge[i].cost);
sort(edge,edge+n*(n-1)/2);//对n*(n-1)/2个元素按<排序形式排序
for(int i=0;i<n;i++) tree[i]=-1;//初始化并查集
int ans=0;
for(int i=0;i<n*(n-1)/2;i++){//将最小生成树的各顶点加入并查集中
int a=findroot(edge[i].a);
int b=findroot(edge[i].b);
if(a!=b) {
tree[a]=b;//已经加过的不需要再加了,没加的要加入
ans+=edge[i].cost;//将未加入 并查集的元素加入后还要把其权值加上
}
}
printf("%d\n\n",ans);
}
return 0;
}
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
来源:CSDN
作者:缘奈酱
链接:https://blog.csdn.net/qq_44249650/article/details/104022544