求集合里元素的个数 输出最大的个数是多少
Sample Input
4
1 2
3 4
5 6
1 6
4
1 2
3 4
5 6
7 8
Sample Output
4
2
1 # include <iostream> 2 # include <cstdio> 3 # include <cstring> 4 # include <algorithm> 5 # include <cmath> 6 # include <queue> 7 # define LL long long 8 using namespace std ; 9 10 const int MAXN = 10000010; 11 int F[MAXN]; 12 int num[MAXN] ; 13 14 int find(int x)//找x的祖先结点 15 { 16 if(F[x]==x) return x; 17 return F[x]=find(F[x]); 18 } 19 void bing(int u,int v) //按秩合并 20 { 21 int x = find(u); 22 int y = find(v); 23 if(x == y) 24 return ; 25 if(num[x] >= num[y]) 26 { 27 F[y] = x; 28 num[x] += num[y]; 29 } 30 else 31 { 32 F[x] = y; 33 num[y] += num[x]; 34 } 35 } 36 int main() 37 { 38 //freopen("in.txt","r",stdin) ; 39 int n ; 40 while(scanf("%d",&n) != EOF) 41 { 42 if (n == 0) 43 { 44 printf("1\n") ; 45 continue ; 46 } 47 int i ; 48 for(i = 1 ; i <= MAXN ; i++) 49 { 50 F[i] = i ; 51 num[i] = 1 ; 52 } 53 int u , v , t = 0 ; 54 for(i = 1 ; i <= n ; i++) 55 { 56 scanf("%d %d" , &u , &v) ; 57 bing(u,v) ; 58 t = max(t , max(u , v)) ; 59 } 60 int Max = 0 ; 61 for(i = 1 ; i <= t ; i++) 62 if (num[i] > Max) 63 Max = num[i] ; 64 printf("%d\n" , Max) ; 65 66 } 67 return 0; 68 }
时间: 2024-10-28 11:21:35