HDOJ 1879 繼續暢通工程

~~~題目鏈接~~~


code:

#include <stdio.h>
#include <algorithm>
using namespace std;
class node
{
    public:
        int x, y, c, flag;
        bool operator< (const node &s) const
        {
            return c<s.c;
        }
}tree[5005];
int n = 0, sum = 0, f[102], r[102];

void init()
{
    for(int i = 0; i<102; i++)
    {
        f[i] = i;
        r[i] = 0;
    }
}

int find(int x)
{
    if(f[x] != x)
        f[x] =find(f[x]);
    return f[x];
}

void Union(int x, int y)
{
    if(r[x]<r[y])
        f[x] = y;
    else
    {
        if(r[x] == r[y])
            r[x]++;
        f[y] = x;
    }
}

void Kruskal()
{
    int i = 0, x = 0, y = 0, c = 0, fx = 0, fy = 0;
    for(i = 0; i<n*(n-1)/2; i++)
    {
        x = tree[i].x;
        y = tree[i].y;
        c = tree[i].c;
        fx = find(x), fy = find(y);
        if(fx == fy) continue;
        else
        {
            Union(fx, fy);
            sum += c;
        }
    }
}

int main()
{
    int i = 0, x = 0, y = 0, c = 0, flag = 0, cnt;
    while(scanf("%d", &n), n)
    {
        sum = cnt = 0;
        init();
        for(i = 0; i<n*(n-1)/2; i++)
        {
            scanf("%d %d %d %d", &x, &y, &c, &flag);
            if(flag)
            {
                //sum += c;
                int fx = find(x), fy = find(y);
                if(fx == fy) continue;
                Union(fx, fy);
            }
            else
            {
                tree[cnt].x = x;
                tree[cnt].y = y;
                tree[cnt++].c = c;
            }
        }
        sort(tree, tree+cnt);
        Kruskal();
        printf("%d\n", sum);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章