Jungle Roads HDU - 1301(最小生成树-并查集)

#include <stdio.h>
#include <algorithm>

using namespace std;

struct Node
{
    int a, b;
    int w;
}list[100];

int t[50];

bool cmp(Node a, Node b)
{
    return a.w < b.w;
}

int findRoot(int x)
{
    if(t[x] == x)
        return x;
    int tmp = findRoot(t[x]);
    t[x] = tmp;
    return tmp;
}

int main()
{
    int n, m, c;
    char a, b;
    while(~scanf("%d", &n) && n != 0)
    {
        int id = 0;
        while(n > 1)
        {
            getchar();   //吃掉换行符 
            scanf("%c %d", &a, &m);
            for(int i = 0; i < m; i++)    //处理输入 
            {
                getchar();   //吃掉空格 
                scanf("%c %d", &b, &c);
                list[id].a = a - 'A' + 1;
                list[id].b = b - 'A' + 1;
                list[id++].w = c;
            }
            n--;                
        }
        sort(list, list+id, cmp);   //排序 
        for(int i = 1; i < 27; i++)
            t[i] = i;
            
        int ans = 0;
        for(int i = 0; i < id; i++)    //按照边权递增的顺序遍历 
        {
            int x1 = findRoot(list[i].a);
            int x2 = findRoot(list[i].b);
            if(x1 != x2)
            {
                t[x1] = x2;
                ans += list[i].w;    
            }
        }
        printf("%d\n", ans);
    }    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/mch2869253130/article/details/82464222