题目1017:还是畅通工程

来源:互联网 发布:html5 js弹出键盘事件 编辑:程序博客网 时间:2024/06/07 00:29
// 克鲁斯卡尔算法,对边的权值从小到大排序 
#include<stdio.h>
#include<algorithm>
using namespace std;
#define N 101
int Tree[N];
int findRoot(int x){            // 查找该结点的根结点 
    if(Tree[x]==-1) return x;
    else{
        int tmp=findRoot(Tree[x]);
        Tree[x]=tmp;
        return tmp;    
    }    
}
struct Edge{    // 边结构体 
    int a,b;    // 边的两个结点编号
    int cost;   // 该边的权值
    bool operator < (const Edge &A) const{
        return cost<A.cost;    
    }    
}edge[6000];
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+1,edge+1+n*(n-1)/2);
        for(int i=1;i<=n;i++) Tree[i]=-1;     // 初始化为孤立集合 
        int ans=0;                            // 最小生成树的权值和 
        for(int i=1;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",ans);
    }
    return 0;    
}
0 0
原创粉丝点击