HDOJ 1856 More is better

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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
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;
}

发布者

Tanky Woo

Tanky Woo,[个人主页:https://tankywoo.com] / [新博客:https://blog.tankywoo.com]

发表评论

电子邮件地址不会被公开。 必填项已用*标注