Ubiquitous Religions(sdut_2428)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int a[50010];
int find(int x)
{
    while(x != a[x]){
        x = a[x];
    }
    return x;
}
void merge(int x, int y)
{
    int f1, f2;
    f1 = find(x);
    f2 = find(y);
    if(f1 != f2){
        a[f1] = f2;
    }
}
int main()
{
    int n, m;
    int digit = 1;
    while(~scanf("%d %d", &n, &m)){
        if(n == 0 && m == 0){
            break;
        }
        int i;
        for(i = 1;i <= n;i++){
            a[i] = i;
        }
        int x, y;
        for(i = 0;i < m;i++){
            scanf("%d %d", &x, &y);
            merge(x,y);
        }
        int sum = 0;
        for(i = 1;i <= n;i++){
            if(a[i] == i){
                sum++;
            }
        }
        printf("Case %d: %d\n", digit, sum);
        digit++;
    }

    return 0;
}

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