【九度OJ】题目1444:More is better 解题报告

标签(空格分隔): 九度OJ

 

题目描述:

Mr Wang wants some boys to help him with a project. Because the project is rather complex, the more boys come, the better it will be. Of course there are certain requirements.Mr Wang selected a room big enough to hold the boys. The boy who are not been chosen has to leave the room immediately. There are 10000000 boys in the room numbered from 1 to 10000000 at the very beginning. After Mr Wang’s selection any two of them who are still in this room should be friends (direct or indirect), or there is only one boy left. Given all the direct friend-pairs, you should decide the best way.

输入:

The first line of the input contains an integer n (0 ≤ n ≤ 100 000) - the number of direct friend-pairs. The following n lines each contains a pair of numbers A and B separated by a single space that suggests A and B are direct friends. (A ≠ B, 1 ≤ A, B ≤ 10000000)

输出:

The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.

样例输入:

4
1 2
3 4
5 6
1 6
4
1 2
3 4
5 6
7 8

样例输出:

4
2

Ways

这个是图论中的并查集的问题,本来不难的问题,结果又让我搞的很麻烦。

错误的地方一个在应该给每个人的朋友数量初始化为1,这样的话才能表示以他为根元素的所有人的数量。

第二个地方在没有理解a,b谁是根的问题。注意Tree[aRoot] = bRoot;时说明了b是根。
friends[bRoot] += friends[aRoot];这句很重要,说明了以b为根的朋友的总数量的增加值应该是以a为根的元素的数量。深刻理解这句话,不要搞反,另外,不能这句不要出现a,b。

为了防止弄错,可以按照书上的来,直接把查找到的根元素赋值给a,b,即可防止出错。

#include<stdio.h>

#define size 10000001
int Tree[size];
int friends[size];

int findRoot(int x) {
    if (Tree[x] == -1) {
        return x;
    } else {
        int temp = findRoot(Tree[x]);
        Tree[x] = temp;
        return temp;
    }
}

int main() {
    int n;
    while (scanf("%d", &n) != EOF) {
        for (int i = 1; i < size; i++) {
            Tree[i] = -1;
            friends[i] = 1;//初始为1
        }
        while (n-- != 0) {
            int a, b;
            scanf("%d%d", &a, &b);
            int aRoot = findRoot(a);
            int bRoot = findRoot(b);
            if (aRoot != bRoot) {
                Tree[aRoot] = bRoot;
                friends[bRoot] += friends[aRoot];//深刻理解。
            }
        }
        int answer = 1;
        for (int i = 1; i <= size; i++) {
            if (Tree[i] == -1 && friends[i] > answer) {
                answer = friends[i];
            }
        }
        printf("%d\n", answer);
    }
    return 0;
}

Date

2017 年 3 月 9 日