POJ2524(并查集)

大意:调查宗教,n个人m组数据,每组数据a,b表示a,b同一种,求一共几种。

分析:并查集。

代码

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int pre[50005];
bool t[50005];
int find(int x)
{
    if(pre[x]==x)
        return x;
    else
        return pre[x]=find(pre[x]);
}
void mix(int x, int y)
{
    int fx = find(x), fy = find(y);
    if (fx != fy)
        pre[fy] = fx;
}
int main()
{
    int n, m,num=0;
    while (scanf("%d%d",&n,&m)!=EOF&&n)
    {
        int a, b,sum=0;
        for (int i = 1; i <= n; i++)
            pre[i]=i;
        for (int i = 0; i < m; i++)
        {
            scanf("%d%d", &a, &b);
            mix(a, b);
        }
        memset(t, 0, sizeof(t));
        for (int i = 1; i <= n; i++)
            t[find(i)] = 1;
        for (int i = 1; i <= n; i++)
            if (t[i])
                sum++;
        num++;
        printf("Case %d: %d\n",num, sum);
    }
    return 0;
}


posted @ 2016-04-25 12:55  Nickqiao  阅读(124)  评论(0编辑  收藏  举报