题目描述:

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



#include<iostream>
#include<stdio.h>
#include<algorithm>
#define N 10000001
//将一个数定义在预处理部分 
using namespace std;
int path[N];
int sum[N]; 
int findroot(int a){
    int temp=a;
    while (path[a] != -1){
        a=path[a];
    }
    int temp2;
    //改进,使树的高度变矮,宽度增加,方便找根 
    while (path[temp]!= -1){
        temp2=path[temp];
        path[temp]=a;
        temp=temp2;
    }
    return a;
}

int main (){
    int n;
    while (cin>>n){
        for (int i=1;i<=N;i++){
            path[i]=-1; sum[i]=1;
        }
        int ans=0;
        int a,b;
        while (n--){
            cin >>a>>b;
            a=findroot(a);
            b=findroot(b);
            if (a!=b){
                path[a]=b;
                sum[b]+=sum[a];
                sum[a]=0;
            } 
        }
        for (int i=1;i<=N;i++){
            if (sum[i] > ans)
            ans =sum[i];
        }
        cout<<ans<<endl;
    } 
    return 0;
}

 

跟上一道畅通工程几乎一样

加了一个在合并集合时同时合并(加)元素个数的功能

ps:不能想着在找根的过程中数元素个数,因为不一定是叶子,数出来的不对,