【算法筆記第9.6節-並查集】問題 D: More is better

題目描述

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.

樣例輸入

3
1 3
1 5
2 5
4
3 2
3 4
1 6
2 6

樣例輸出

4
5

題目說的是現在有一個項目需要一個隊伍完成,而且隊伍人數越多越好。

現在有10000000個人,給你一些兩人之間的聯繫,讓你輸出隊伍人數最多的人的數量。

#include<stdio.h>
#include<string.h>
int f[10000001];
int num[10000001];
int findFather(int x)
{
    if(x==f[x]) return x;
    else
    {
        int F = findFather(f[x]);
        f[x] = F;
        return F;
    }
}
void Union(int a, int b)
{
    int fa = findFather(a);
    int fb = findFather(b);
    if(fa!=fb)
        f[fa] = fb;
}
int main()
{
    int m;
    while(scanf("%d",&m)!=EOF)
    {
        memset(num, 0, sizeof(num));
        for(int i=1; i<=10000000; i++)
            f[i] = i;
        int a, b;
        for(int i=0; i<m; i++)
        {
            scanf("%d%d",&a, &b);
            Union(a, b);
        }
        int ans = 0;
        for(int i=1; i<=10000000; i++)
        {
            num[findFather(i)]++;
        }
        int maxn = 1;
        for(int i=1; i<=10000000; i++)
        {
            if(maxn < num[i])
                maxn = num[i];
        }
        printf("%d\n", maxn);
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章