POJ 1251 Jungle Roads

题意:嗯……没看题……看了眼图……求个最小生成树。

 

解法:kruskal。

 

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<math.h>
#include<limits.h>
#include<time.h>
#include<stdlib.h>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#define LL long long

using namespace std;

struct node
{
    int u, v, val;
    bool operator < (const node &tmp) const
    {
        return val < tmp.val;
    }
}edge[10005];
int father[105];
int Find(int a)
{
    if(a != father[a]) father[a] = Find(father[a]);
    return father[a];
}
bool Union(int a, int b)
{
    int c = Find(a), d = Find(b);
    if(c == d) return false;
    father[c] = d;
    return true;
}
int main()
{
    int n;
    while(~scanf("%d", &n) && n)
    {
        int cnt = 0;
        for(int i = 1; i <= n; i++)
            father[i] = i;
        for(int i = 1; i < n; i++)
        {
            char ch[2];
            int k;
            scanf("%s%d", ch, &k);
            int u = ch[0] - 'A' + 1;
            while(k--)
            {
                int x;
                scanf("%s%d", ch, &x);
                edge[cnt].u = u;
                edge[cnt].v = ch[0] - 'A' + 1;
                edge[cnt++].val = x;
            }
        }
        sort(edge, edge + cnt);
        int ans = 0;
        for(int i = 0; i < cnt; i++)
        {
            if(Union(edge[i].u, edge[i].v)) ans += edge[i].val;
        }
        printf("%d\n", ans);
    }
    return 0;
}

  就不告诉你们是2421的代码改的……

posted @ 2015-10-02 22:39  露儿大人  阅读(120)  评论(0编辑  收藏  举报