POJ.2524 Ubiquitous Religions (并查集)

POJ.2524 Ubiquitous Religions (并查集)

题意分析

学校共有n个人,先给出m组信息,求问学校最多有多少种宗教信仰信奉者。
每组信息包括a,b两个人,表示a,b两人信奉同一种宗教。

初始化集合时,把每一个人都当做一个宗教。 读入信息时,如果发现2个人信奉的宗教不同(根节点祖先不同),合并这两个人,并使得宗教总数目-1, 最后输答案即可。

代码总览

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#define INF 0x3f3f3f3f
#define nmax 50005
#define MEM(x) memset(x,0,sizeof(x))
using namespace std;
int father[nmax];
int rnk[nmax],ans;
void makeset(int x)
{
    father[x] = x;
    rnk[x] = 0;
}
int findset(int x)
{
    int r  = x,temp;
    while(father[r] != r) r = father[r];
    while(x != r){
        temp = father[x];
        father[x] = r;
        x = temp;
    }
    return r;
}
void unionset(int x, int y)
{
    x = findset(x);
    y = findset(y);
    if(x == y) return;
    ans --;
    if(rnk[x] > rnk[y]){
        father[y] = x;
    }else{
        father[x] = y;
        if(rnk[x] == rnk[y])
            rnk[x] ++;
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    int n,m,kase = 1;
    while(scanf("%d%d",&n,&m) != EOF){
        if(n == 0 && m == 0) break;
        for(int i = 1; i<=n;++i) makeset(i);
        ans = n;
        for(int i = 0; i<m; ++i){
            int a,b;
            scanf("%d%d",&a,&b);
            unionset(a,b);
        }
        printf("Case %d: %d\n",kase++,ans);
    }
    return 0;
}
posted @ 2017-05-02 13:05  pengwill  阅读(80)  评论(0编辑  收藏  举报