5.3畅通工程-MST最小生成树

谁说胖子不能爱 提交于 2020-01-25 02:39:55

在这里插入图片描述
在这里插入图片描述

#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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!