HDU1301 Jungle Roads

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

const int maxn = 30;
const int maxm = 500;

struct Edge{
    int  v1, v2;
    int 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];

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


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


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(){
    char v1, v2;
    int weight, m;
    while(cin>>n&&n){
        Init();
        n=n-1;
        while(n--){
            cin>>v1>>m;
            while(m--){
                cin>>v2>>weight;
                E[cnt++] = Edge(v1-'A', v2-'A', 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、付费专栏及课程。

余额充值