POJ2524Ubiquitous Religions, 1611The Suspects(并查集)

POJ2524 Ubiquitous Religions

POJ1611 The Suspects

解题报告:

这两个题差不多。就一块发了。。就是赤裸裸的并查集

POJ2524Ubiquitous Religions代码如下:

View Code
#include <stdio.h>
#include <stdlib.h>
#define MAXN 50010
int p[MAXN];
int icount;
int find_f(int x){return p[x] == x ? x : (p[x]=find_f(p[x]));}
int main(){
    int n, m, i, a, b;
    int cn=0;
    while(scanf("%d %d", &n, &m) == 2 && (n != 0 || m != 0)){
        cn++; icount = n;
        for(i=1; i<=n; i++) p[i] = i;
        for(i=0; i<m; i++){
            scanf("%d %d", &a, &b);
            int x = find_f(a), y = find_f(b);
            if(x != y) {p[x] = y; icount--;}
        }
        printf("Case %d: %d\n", cn, icount);
    }
    return 0;
}

 

POJ1611 The Suspects代码如下:

View Code
#include <stdio.h>
#include <stdlib.h>
#define MAXN 30010
int p[MAXN];
int find_f(int x){return p[x] == x ? x : (p[x]=find_f(p[x]));}
int main(){
    int n, m, i, a, b, cnt, k;
    while(scanf("%d %d", &n, &m) == 2 && (n != 0 || m != 0)){
        cnt = 0;
        for(i=0; i<n; i++) p[i] = i;
        for(i=0; i<m; i++){
            scanf("%d", &k);
            if((k--)>0) scanf("%d", &a);
            while(k--){
                scanf("%d", &b);
                int x = find_f(a), y = find_f(b);
                if(x != y) p[x] = y;
            }
        }
        int t = find_f(0);
        for(i=0; i<n; i++) if(find_f(i) == t) cnt++;
        printf("%d\n", cnt);
    }
    return 0;
}

 

 

posted on 2013-02-21 14:10  Still_Raining  阅读(174)  评论(0编辑  收藏  举报