hdu More is better

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

题意:王老师要找一些男生帮助他完成一项工程。要求最后挑选出的男生之间都是朋友关系,可以说直接的,也可以是间接地。问最多可以挑选出几个男生(最少挑一个)。
         这是一个有关并查集的题目。只不过不是求有几个集合,而是求每个集合中元素的个数,进而求出个数的最大值。和求集合个数的方法差不多,只需要在合并两个集合时处理一下,让这两个集合的元素个数也合并一下就行了。接下来只需要找出最大值即可。要注意的一个地方就是:当n=0时,要输出1。
 
各种坑......
 
代码:
 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <math.h>
 4 #include <algorithm>
 5 #include <iostream>
 6 #include <ctype.h>
 7 #include <iomanip>
 8 #include <queue>
 9 #include <stdlib.h>
10 using namespace std;
11 
12 int f[10000010],num[10000010];
13 int n,m;
14 
15 void init()
16 {
17     for(int i=0;i<=10000010;i++){
18         f[i]=i;
19         num[i]=1;
20     }
21 }
22 
23 int find(int x)
24 {
25     if(x!=f[x])
26         f[x]=find(f[x]);
27     return f[x];
28 }
29 
30 void Union(int x,int y)
31 {
32     int p=find(x);
33     int q=find(y);
34     if(p != q){  
35         f[p] = q;
36         num[q]+=num[p];
37     }
38 }
39 
40 int main()
41 {
42     int n,m,i,j,a,b;
43     while(~scanf("%d",&n)){
44         if(n==0){
45             printf("1
");  
46             continue;  
47         }
48         init();
49         int max=0;
50         for(i=0;i<n;i++){
51             scanf("%d%d",&a,&b);
52             Union(a,b);
53         }
54         for(j=0;j<=10000010;j++){
55             if(num[j]>max)
56                 max=num[j];
57         }
58         printf("%d
",max);
59     }
60 }
原文地址:https://www.cnblogs.com/wangmengmeng/p/4957418.html