Blog·Tanky WooABOUTRSS

HDOJ 1856 More is better

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

题目地址: http://acm.hdu.edu.cn/showproblem.php?pid=1856


并查集~~~ 这题有问题,在对待n==0的情况时,标程是输出为1,而按理应该是0~~~ 经果冻布丁提醒,题目是对的,有这么一句话:or there is only one boy left

#include 
using namespace std;

#define MAX 10000001

// 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] = 1;
    }
}

// 查找
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;
        rank[x] += rank[y];
    }
    else if(rank[x] < rank[y])
    {
        father[x] = y;
        rank[y] += rank[x];
    }
    else
    {
        father[x] = y;
        //rank[y]++;
        rank[y] += rank[x];
    }

}

int main()
{
    //freopen("input.txt", "r", stdin);
    int a, b;
    int nNum;
    while(scanf("%d", &nNum;) != EOF)
    {
        Make_Set(MAX);
        if(nNum==0)
        {
            printf("1\n");
            continue;
        }
        for(int i=0; i<nNum; ++i)
        {
            scanf("%d %d", &a, &b);
            Union(a, b);
            //printf("rank[%d]=%d rank[%d]=%d\n", a, rank[a], b, rank[b]);
        }
        int _max=0;
        for(int i=0; i<=MAX; ++i)
            //printf("%d ", rank[i]);
            if(_max < rank[i])
                _max = rank[i];
        printf("%d\n", _max);
    }
    return 0;
}