POJ 1611 The Suspects
题目大意就是找到所有可能被传染的人数,题意挺容易理解的。很容易联想到用并查集去做,将每组除第一个人之外都加到第一个人所在的集合,这样输出与0在一个集合的元素个数就是所求。
AC code:
1 #include <iostream>
2 #define MAX 30001
3 using namespace std;
4 int father[MAX], num[MAX];
5 int n, m;
6
7 void ini(int n)
8 {
9 for(int i = 0; i < n; i++)
10 {
11 father[i] = i;
12 num[i] = 1;
13 }
14 }
15 int get_father(int x)
16 {
17 return x == father[x] ? x : father[x] = get_father(father[x]);
18 }
19 void Union(int a, int b)
20 {
21 int x = get_father(a);
22 int y = get_father(b);
23 if(x == y)
24 return;
25 if(num[x] >= num[y])
26 {
27 father[y] = x;
28 num[x] += num[y];
29 }
30 else
31 {
32 father[x] = y;
33 num[y] += num[x];
34 }
35 }
36 int main()
37 {
38 while(scanf("%d%d", &n, &m)!=EOF && n)
39 {
40 ini(n);//初始化
41 for(int i = 0; i < m; i++)
42 {
43 int k, first, temp;
44 scanf("%d%d", &k, &first);
45 for(int j = 1; j < k; j++)
46 {
47 scanf("%d", &temp);
48 Union(first, temp);//把每组第一个元素所在集合与后面的数连在一起
49 }
50 }
51 printf("%d\n", num[get_father(0)]);
52 }
53 return 0;
54 }