hdu 1233 还是畅通工程(最小生成树,kruskal,前向星)

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1233

#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct Edge{
    int from,to,w;
    bool operator<(const Edge b)const{
        return w<b.w;
    }
}edge[5000];
int father[100];
int find(int a){
    if(father[a]==a)return a;
    return find(father[a]);
}
int kruskal(int n){
    int ans=0,top=0,i;
    for(i=1;i<=n;i++){
        father[i]=i;
    }
    for(i=0;i<n*(n-1)/2;i++){
        if(top==n-1)break;
        int q1=find(edge[i].from),q2=find(edge[i].to);
        if(q1!=q2){
                ans+=edge[i].w;
                father[q1]=q2;
                top++;
        }
    }
    return ans;
}
int main()
{
    //freopen("cin.txt","r",stdin);
    int n,i;
    while(cin>>n&&n){
        memset(father,0,sizeof(father));
        for(i=0;i<n*(n-1)/2;i++){
            int a,b,c;
            scanf("%d%d%d",&a,&b,&c);
            edge[i].from=a;
            edge[i].to=b;
            edge[i].w=c;
        }
        sort(edge,edge+n*(n-1)/2);
        printf("%d\n",kruskal(n));
    }
    return 0;
}


你可能感兴趣的:(HDU,kruskal)