POJ2524Ubiquitous Religions, 1611The Suspects(并查集)

本文介绍了如何使用并查集算法解决POJ2524UbiquitousReligions与POJ1611TheSuspects两个问题,并提供了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

 

 

转载于:https://www.cnblogs.com/tanhehe/archive/2013/02/21/2920507.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值