码迷,mamicode.com
首页 > 其他好文 > 详细

nyoj Jungle Roads (最小生成树)

时间:2015-03-13 20:36:45      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

Kruskal

#include "iostream"
#include "algorithm"
using namespace std;
#define MAXN 1111
struct node {
    int x, y, l;
}p[MAXN];
int fa[MAXN];
int n, m, k;
int re, num;

bool cmp(node a, node b)
{
    return a.l < b.l;
}

int findset(int x)
{
    if (fa[x] == x) return x;
    return  fa[x] = findset(fa[x]);
}

void merg(int x, int y)
{
    int fx = findset(x);
    int fy = findset(y);
    if (fx != fy)
        fa[fy] = fx;
}

void init(int n)
{
    for (int i = 0; i <= n; ++i)
        fa[i] = i;
    num = 0;
    re = 0;
}

int main()
{
    int n, w, t;
    char ch, z;
    while (cin >> n, n) {
        init(n);
        for (int i = 1; i < n; ++i) {
            cin >> z >> t;
            z -= A;
            for (int j = 0; j < t; ++j) {
                cin >> ch;
                cin >> w;
                p[num].x = z;
                p[num].y = ch - A;
                p[num++].l = w;
            }
        }
        sort(p, p + num, cmp);
        for (int i = 0; i < num; ++i) {
            int x = findset(p[i].x);
            int y = findset(p[i].y);
            if (x != y) {
                fa[y] = x;
                re += p[i].l;
            }
        }
        cout << re << endl;
    }
    return 0;
}

 

nyoj Jungle Roads (最小生成树)

标签:

原文地址:http://www.cnblogs.com/usedrosee/p/4335845.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!