HDOJ 1879 继续畅通工程

来源:互联网 发布:qq空间淘宝应用可信吗 编辑:程序博客网 时间:2024/06/10 09:00

~~~题目链接~~~


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;}