POJ-2524 Ubiquitous Religions (并查集)

Input
The input consists of a number of cases. Each case starts with a line specifying the integers n and m. The next m lines each consists of two integers i and j, specifying that students i and j believe in the same religion. The students are numbered 1 to n. The end of input is specified by a line in which n = m = 0.
Output
For each test case, print on a single line the case number (starting with 1) followed by the maximum number of different religions that the students in the university believe in.
题意:
给出n个学生,并编号1-n (0 < n <= 50000).然后对其中m个进行寻问(m个关系),得到a b为同一个宗教信仰,然后统计总共有多少种信仰(没有出现的学生默认单独为一种)
思路:
此题就是最简单的利用并查集,我们将信仰相同的学生合并在一起(unite)然后再统计pre[i] 等于自身的个数,即为最后统计个数
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 100005;
int pre[maxn];
int ran[maxn];
int vis[maxn];//用于统计是否出现过 
int n,m,cnt;
int find(int x){
    if(x!=pre[x]) return pre[x] = find(pre[x]);
    else return pre[x];
}
void unite(int x,int y){
    x = find(x),y = find(y);
    if(x!=y){
        if(ran[x]>=ran[y]){
            ran[x]++;
            pre[y] = x;
        }
        else {
            ran[y]++;
            pre[x] = pre[y];
        }
    }
    else return;
}
void init(){
    for(int i=1;i<=n;i++){
        pre[i] = i;
        ran[i] = 0;
    }
}
int main(){
    cnt = 0;
    while(~scanf("%d%d",&n,&m)){
        if(n==0&m==0) break;
        int ans = 0;
        init();
        for(int i=1;i<=m;i++){
            int x,y;
            scanf("%d%d",&x,&y);
            unite(x,y);        
        }
        for(int i=1;i<=n;i++){
            if(pre[i] == i) ans++;
        }
        printf("Case %d: %d\n",++cnt,ans);
    }    
} 

 

转载于:https://www.cnblogs.com/Tianwell/p/11195071.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值