poj 1611 求0号结点所在集合的元素个数
求0号结点所在集合的元素个数
Sample Input
100 4
2 1 2
5 10 13 11 12 14
2 0 1
2 99 2
200 2
1 5
5 1 2 3 4 5
1 0
0 0
Sample Output
4
1
1
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 = 30010; 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 , m , k ; 40 while(scanf("%d %d", &n , &m) != EOF) 41 { 42 if (n == 0 && m == 0) 43 break ; 44 45 int i ; 46 for(i = 0 ; i < n ; i++) 47 { 48 F[i] = i ; 49 num[i] = 1 ; 50 } 51 int u , v ; 52 while(m--) 53 { 54 scanf("%d %d" , &k , &u) ; 55 k-- ; 56 while(k--) 57 { 58 scanf("%d" , &v) ; 59 bing(u , v) ; 60 } 61 } 62 printf("%d\n" , num[find(0)]) ; //集合元素的个数保存在祖先结点的num数组里 63 64 65 } 66 return 0; 67 }