并查集,求和0号同集合的点有多少个。

 1 #include <stdio.h>
 2 #include <string.h>
 3 #define N 30005
 4 int fa[N],num[N];
 5 int find(int a)
 6 {
 7     if(fa[a] == a) return a;
 8     return fa[a] = find(fa[a]);
 9 }
10 void unin(int a,int b)
11 {
12     a = find(a);
13     b = find(b);
14     if(a == b) return;
15     if(num[a] >= num[b])
16     {
17         fa[b] = a;
18         num[a] += num[b];
19     }
20     else
21     {
22         fa[a] = b;
23         num[b] += num[a];
24     }
25 }
26 int main()
27 {
28     int n,m,i,t,a,b;
29     while(scanf("%d%d",&n,&m),n||m)
30     {
31         for(i = 0; i < n; i++)
32         {
33             fa[i] = i;
34             num[i] = 1;
35         }
36         while(m--)
37         {
38             scanf("%d %d",&t,&a);
39             while(--t)
40             {
41                 scanf("%d",&b);
42                 unin(a,b);
43             }
44         }
45         printf("%d\n",num[find(0)]);
46     }
47     return 0;
48 }