HDU 1856 More is better 并查集(基础模板题)

题意:先输入n,然后输入n行,同一行的两个数表示的互为朋友,要求找到最多的直接朋友或间接朋友。比如

4
1 2
3 4
5 6
1 6
其中1、2、5、6是朋友,3、4是朋友,所以输出4
测试样例:
4
1 2
3 4
5 6
1 6
4
1 2
3 4
5 6
7 8
输出
4
2
注意:init()写在while循环里面,注意n=0的特殊情况,注意数据范围!

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<algorithm>
 5 using namespace std;
 6 int n,p,q;
 7 int f[10000010],num[10000010];
 8 void init()
 9 {
10     for(int i=1;i<10000010;i++)
11     {
12         f[i]=i;
13         num[i]=1;
14     }
15 }
16 int find(int x)
17 {
18     if(f[x]!=x)
19     return f[x]=find(f[x]);
20 }
21 void merge(int x,int y)
22 {
23     int tx=find(x);
24     int ty=find(y);
25     if(tx!=ty)
26     {
27         f[tx]=ty;
28         num[ty]+=num[tx];
29     }
30 return ;
31 }
32 int main()
33 {
34     while(~scanf("%d",&n))
35     {
36       init();
37       if(n==0)
38       {
39        printf("1
");
40        continue; 
41       }
42       int maxn=0;
43       while(n--)
44       {
45           cin>>p>>q;
46           if(p>maxn)
47           {
48               maxn=p;
49         } 
50         if(q>maxn)
51         {
52             maxn=q;
53         }
54         merge(p,q); 
55       }
56       int Max=0;    
57      for(int i=1;i<=maxn;i++)
58      {
59      //    cout<<num[i]<<endl; 
60          if(num[i]>Max)
61          {
62              Max=num[i];
63         } 
64      }
65      cout<<Max<<endl; 
66     // Max=0;
67     }
68 return 0;
69 } 
原文地址:https://www.cnblogs.com/1013star/p/9267940.html