您的位置:首页 > 其它

poj2524

2011-05-17 19:23 281 查看
简单并查集

View Code

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

#define maxn 50004

int father[maxn];

int getanc(int a)
{
if (father[a] == a)
return a;
return father[a] = getanc(father[a]);
}

void merge(int a, int b)
{
if (father[a] == -1)
father[a] = a;
if (father[b] == -1)
father[b] = b;
father[getanc(a)] = getanc(b);
}

int main()
{
//    freopen("t.txt", "r", stdin);
int t = 0;
int n, m;
while (scanf("%d%d", &n, &m), n | m)
{
memset(father, -1, sizeof(father));
t++;
for (int i = 0; i < m; i++)
{
int a, b;
scanf("%d%d", &a, &b);
a--;
b--;
merge(a, b);
}
int ans = 0;
for (int i = 0; i < n; i++)
if (father[i] == -1 || father[i] == i)
ans++;
printf("Case %d: %d\n", t, ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: