您的位置:首页 > 其它

hdu_1301 Jungle Roads

2015-04-25 09:47 253 查看
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define N 100005
using namespace std;
int father
;
struct node
{
    int u,v,w;
}save
;

int cmp(node a,node b)
{
    return a.w < b.w;
}
void Make_set(int n)
{
    int i;
    for(i=0; i<=n; i++)
    {
        father[i] = i;
    }
}

int Find_set(int x)
{
    int pre,ans,temp;
    pre = x;
    while(x != father[x])
    {
        x = father[x];
    }
    ans = x;
    while(pre != father[pre])
    {
        temp = father[pre];
        father[pre] = x;
        pre = temp;
    }
    return ans;
}

void Union_set(int a,int b)
{
    int x = Find_set(a);
    int y = Find_set(b);
    if(x > y)
        father[x] = y;
    else
        father[y] = x;
}
int main()
{
    int i,j,k,sum,n,m,x,y,ans,res,value;
    char s,t;
    while(cin>>n,n)
    {
        sum = 0,k = 0;
        for(i=0; i<n-1; i++)
        {
            cin>>s>>m;
            for(j=0; j<m; j++)
            {
                cin>>t>>value;
                save[k].u = s - 'A';
                save[k].v = t - 'A';
                save[k++].w = value;
            }

        }
        sort(save,save+k,cmp);
        /*
        for(i=0; i<k; i++)
            cout<<save[i].u<<" "<<save[i].v<<" "<<save[i].w<<endl;
        */
        Make_set(k);
        for(i=0; i<k; i++)
        {
            x = Find_set(save[i].u);
            y = Find_set(save[i].v);
            if(x != y)
            {
                Union_set(save[i].u,save[i].v);
                sum += save[i].w;
            }
        }
        cout<<sum<<endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: