POJ 2524 Ubiquitous Religions

题目链接:http://poj.org/problem?id=2524


题意一所学校每个同学都信仰一种宗教,只能询问两个同学之间的宗教是否相同,求问有多少种不同的宗教



#include<cstdio>
#include<iostream>
#include<set>
using namespace std;
#define N 55000
int F[N];
int find(int x)
{
    if(F[x] != x)
        F[x] = find(F[x]);
    return F[x];
}
int main ()
{
    int n, m;
    int t = 1;
    while(scanf("%d %d", &n, &m) != EOF)
    {
        if(n == 0 && m == 0) break;
        for(int i = 1; i <= n; i++)
            F[i] = i;

        for(int i = 1; i <= m; i++)
        {
            int a, b;
            scanf("%d %d", &a, &b);

            int fa = find(a);
            int fb = find(b);
            if(fa != fb)
                F[fb] = fa;
        }
        set<int>ans;
        for(int i = 1; i<= n;i++)
            ans.insert(find(F[i]));
        printf("Case %d: %d\n",t++, ans.size());

    }
    return 0;
}


你可能感兴趣的:(POJ 2524 Ubiquitous Religions)