杭电 1856 More is better (并查集求最大集合)

Description

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. 

Input

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)

Output

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

Sample Input

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

Sample Output

4
2

Hint

 
A and B are friends(direct or indirect), B and C are friends(direct or indirect), then A and C are also friends(indirect). In the first sample {1,2,5,6} is the result. In the second sample {1,2},{3,4},{5,6},{7,8} are four kinds of answers.
 
  题意:
    要找一些人完成一项工程。要求最后挑选出的人之间都是朋友关系,可以说直接的,也可以是间接地。问最多可以挑选出几个人(最少挑一个)。
    在基础的并查集上加个数组记录集合的数量。
 
 1 #include<cstdio>
 2 #include<algorithm>
 3 using namespace std;
 4 #define N 10000000
 5 int n,a,b,max0,max1,i,num[N],fa[N];
 6 int find(int a)
 7 {
 8     if(a == fa[a])
 9     {
10         return a;
11     }
12     else
13     {
14         return fa[a]=find(fa[a]);
15     }
16 }
17 void f1(int x,int y)
18 {
19     int nx,ny;
20     nx=find(x);
21     ny=find(y);
22     if(nx != ny)
23     {
24         fa[nx]=ny;
25         num[ny]+=num[nx];        //合并两个集合的数量 
26     }
27 }
28 int main()
29 {
30     while(scanf("%d",&n)!=EOF)
31     {
32         for(i = 1 ; i <= 1e7 ; i++)
33         {
34             fa[i]=i;
35             num[i]=1;        //刚开始集合只有本身 
36         }
37         if(n == 0)
38         {
39             printf("1
");
40             continue;
41         }
42         max0=0;
43         for(i = 0 ; i < n ; i++)
44         {
45             scanf("%d %d",&a,&b);
46             max0=max(max0,max(a,b));        //找出关系中编号最大的人 
47             f1(a,b);
48         }
49         max1=0;
50         for(i = 1 ; i <= max0 ; i++)
51         {
52             if(max1 < num[i])                //比较每个集合的大小 
53             {
54                 max1=num[i];
55             }
56         }
57         printf("%d
",max1);
58     }
59  } 
——将来的你会感谢现在努力的自己。
原文地址:https://www.cnblogs.com/yexiaozi/p/5726154.html