[POJ1611]The Suspects(并查集)

传送门

 

通过并查集统计集合个数,easy

 

——代码

 1 #include <cstdio>
 2 #include <iostream>
 3 #define N 1000001
 4 
 5 int n, m;
 6 int f[N], num[N];
 7 
 8 inline int read()
 9 {
10     int x = 0, f = 1;
11     char ch = getchar();
12     for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1;
13     for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0';
14     return x * f;
15 }
16 
17 inline int find(int x)
18 {
19     return x == f[x] ? x : f[x] = find(f[x]);
20 }
21 
22 inline void connect(int x, int y)
23 {
24     x = find(x);
25     y = find(y);
26     if(x ^ y) f[x] = y, num[y] += num[x];
27 }
28 
29 int main()
30 {
31     int i, j, k, x, y;
32     while(~scanf("%d %d", &n, &m))
33     {
34         if(!n && !m) break;
35         for(i = 0; i <= n; i++) f[i] = i, num[i] = 1;
36         for(i = 1; i <= m; i++)
37         {
38             k = read();
39             if(k) y = read();
40             for(j = 2; j <= k; j++)
41             {
42                 x = read();
43                 connect(x, y);
44                 y = x;
45             }
46         }
47         printf("%d\n", num[find(0)]);
48     }
49     return 0;
50 }
View Code

 

posted @ 2017-06-15 14:38  zht467  阅读(78)  评论(0编辑  收藏  举报