您的位置:首页 > 其它

HDOJ 1879 继续畅通工程

2012-10-09 20:43 337 查看
~~~题目链接~~~

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: