HDU1233畅通工程

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

const int maxn = 105;
const int maxm = 50005;

struct Edge{
    int v1, v2, weight;
    Edge(int v1=0, int v2=0, int weight=0):v1(v1),v2(v2),weight(weight){}
};


int n, ans, cnt;
int parent[maxn];
int Rank[maxn];
 Edge E[maxm];


void Init(){
    ans = 0;
    cnt = 0;
    for(int i = 0; i <= n; i++){
        parent[i] = i;
        Rank[i] = 0;
    }
}

bool cmp(const Edge& lhs, const Edge& rhs){
    return lhs.weight < rhs.weight;
}

int findRoot(int x){
   int tempRoot;
   int root = x;
   while(root != parent[root])
        root = parent[root];
    while(x != root){
        tempRoot = parent[x];
        parent[x] = root;
        x = tempRoot;
    }
      return root;
}

void Union(int x, int y){
    int xRoot = findRoot(x);
    int yRoot = findRoot(y);
    
    if(xRoot == yRoot)
       return ;
    if(Rank[xRoot] < Rank[yRoot])
       parent[xRoot] = yRoot;
    else if(Rank[xRoot] > Rank[yRoot])
       parent[yRoot] = xRoot;
    else {
        parent[xRoot] = parent[yRoot];
        Rank[yRoot] ++;
    }
    
}
void Kruskal(){
    int edgeNum = 0;
    for(int i = 0; i < cnt&& edgeNum != n - 1; ++ i){
        if(findRoot(E[i].v1) == findRoot(E[i].v2))
            continue;
        else {
            Union(E[i].v1,E[i].v2);
            ans += E[i].weight;
            edgeNum++;
        }
    }
}
int main(){
    int v1, v2, weight;
    while(scanf("%d",&n)!=EOF&&n){
        Init();
        for(int i = 0; i < n*(n-1)/2; i++){
          scanf("%d%d%d",&v1,&v2,&weight);
          E[cnt++] = Edge(v1,v2,weight);
       }
       sort(E,E+cnt,cmp);
       Kruskal();
       printf("%d\n",ans);
        
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值