Tanky WooRSS

POJ 2524 Ubiquitous Religions

18 Aug 2010
这篇博客是从旧博客 WordPress 迁移过来,内容可能存在转换异常。

题目地址: http://acm.pku.edu.cn/JudgeOnline/problem?id=2524


题意: 已知有n个大学生,其中有m对宗教信仰相同的学生,请你估算这n个学生中最多有多少种宗教信仰。

还是并查集~~~不在同一个几何里的合并,并把集合数N减一。求最后的N值。

#include 
using namespace std;

#define MAX 500001

// father[x]表示x的父节点
int father[MAX];
// rank[x]表示x的秩
int rank[MAX];

// 初始化
void Make_Set(int n)
{
    for(int i=1; i<=n; ++i)
    {
        father[i] = i;
        rank[i] = 0;
    }
}

// 查找
int Find_Set(int x)
{
    if(x != father[x])
        return Find_Set(father[x]);
    return x;
}

// 合并
void Union(int x, int y)
{
    x = Find_Set(x);
    y = Find_Set(y);
    if(x == y)  // x,y在同一个集合
        return;
    if(rank[x] > rank[y])
        father[y] = x;
    else if(rank[x] < rank[y])
        father[x] = y;
    else
    {
        rank[y]++;
        father[x] = y;
    }
}

int main()
{
    int N, M, a, b;
    int nCases = 1;
    while(scanf("%d %d", &N;, &M;) && (M||N))
    {
        Make_Set(N);
        for(int i=1; i<=M; ++i)
        {
            scanf("%d %d", &a;, &b;);
            a = Find_Set(a);
            b = Find_Set(b);
            //如果a,b不在同一个集合,则合并
            if(a != b)
            {
                N--;
                Union(a, b);
            }
        }
        printf("Case %d: %d\n", nCases++, N);
    }
    return 0;
}