HDU 1233 还是畅通工程。

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1233

x

解题思路:

简单的最小生成树

实现代码:

#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;

const int maxn=101;


struct NodeHeap{
    int x,y, w;
    bool operator <(const NodeHeap & rhs)const{
        return w<rhs.w;
    }
}edges[maxn*maxn];

int f[maxn];

int findfa(int u){
    if(f[u]==u) return u;
    return f[u]=findfa(f[u]);
}

void unit(int u,int v){
    int fu=findfa(u);
    int fv=findfa(v);
    if(fu!=fv)
        f[fu]=fv;
}

int main(){
    int N;
    while(scanf("%d",&N)!=EOF&&N!=0){

        for(int i=0;i<N*(N-1)/2;i++){
            scanf("%d%d%d",&edges[i].x,&edges[i].y,&edges[i].w);
        }
        sort(edges,edges+(N*(N-1)/2));

        for(int i=1;i<=N;i++){
            f[i]=i;
        }

        long long cost=0;
        int k=0;
        for(int i=0;i<(N*(N-1)/2);i++){

            if(findfa(edges[i].x)!=findfa(edges[i].y)){
                unit(edges[i].x,edges[i].y);
                cost+=edges[i].w;
                k++;

            }

            if(k==N-1){
                break;
            }
        }

        printf("%d\n",cost);
    }
    return 0;

}

 

posted on 2017-03-04 14:59  mkfoy  阅读(114)  评论(0编辑  收藏  举报

导航