首页 > 其他 > 详细

nyoj Jungle Roads (最小生成树)

时间:2015-03-13 20:34:59      阅读:287      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!