pku 2524 Ubiquitous Religions

http://poj.org/problem?id=2524

题目分类是分治,我不知道怎么用分治。并查集1y.注意这里每个人最多有一个宗教信仰

View Code
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#define maxn 50007
using namespace std;
int f[maxn];
int find(int x)
{
if (x != f[x])
f[x] = find(f[x]);
return f[x];
}
void Union(int x,int y)
{
x = find(x);
y = find(y);
if (x != y)
f[y] = x;
}
int main()
{
int i,n,m,count;
int cas = 1;
int a,b;
while (scanf("%d%d",&n,&m))
{
if (!n && !m) break;
for (i = 0; i <= n; ++i)
f[i] = i;
for (i = 0; i < m; ++i)
{
scanf("%d%d",&a,&b);
Union(a,b);
}
//for (i = 1; i <= n; ++i)
//printf("%d ",find(i));
//printf("\n");
count = 0;
for (i = 1; i <= n; ++i)
{
if (i != find(i))
count++;
}
printf("Case %d: %d\n",cas++,n - count);
}
return 0;
}



posted @ 2012-02-24 21:51  E_star  阅读(163)  评论(0编辑  收藏  举报