POJ 1611 The Suspects

http://poj.org/problem?id=1611

简单并查集

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 int father[32002];
 5 void init(int n)
 6 {
 7     int i;
 8     for(i=0;i<=n;i++)
 9         father[i]=i;
10 }
11 int find_father(int child)
12 {
13     if(father[child]==child)
14         return child;
15     father[child]=find_father(father[child]);
16     return father[child];
17 }
18 void Union(int a,int b)
19 {
20     int f_a=find_father(a);
21     int f_b=find_father(b);
22     father[f_a]=f_b;
23 }
24 
25 
26 int main()
27 {
28     int n,m;
29     while(scanf("%d%d",&n,&m)!=EOF) {
30         if(n==0&&m==0)
31             return 0;
32         int i,j,num,a,b;
33         init(n);
34         for(i=0;i<m;i++) {
35             scanf("%d",&num);
36             scanf("%d",&a);    
37             for(j=1;j<num;j++) {
38                 scanf("%d",&b);
39                 Union(a,b);
40             }
41         }
42         int count=0;
43         for(i=0;i<n;i++) {
44             if(find_father(i)==find_father(0))
45                 count++;
46         }
47         printf("%d\n",count);
48     }
49     return 0;
50 }
原文地址:https://www.cnblogs.com/yangce/p/2938072.html