POJ_1611_The Suspects(简单并查集的应用)

题意:

SARS病毒具有传染性;输入学生数编号为0-N,再输入学生groups;每个groups中只要有一个人是SARS的suspects那么这个groups都是;假设 0 号是SARS的怀疑者,让你计算所有的嫌疑人。

100 4
2 1 2
5 10 13 11 12 14
2 0 1
2 99 2
200 2

100是学生人数,4是groups数;

下面4行是groups的信息,第一个数是这个小组有多少人;

后面是分别是学生编号。

 1 # include <stdio.h>
 2 # include <string.h>
 3 # define MAXN 30003
 4 int pre[MAXN];
 5 int num[MAXN];
 6 void Input()
 7 {
 8     int i;
 9     for(i=0;i<MAXN;i++)
10     {
11         num[i]=1; //记录父亲节点所在集合的个数
12         pre[i]=i; //记录父亲节点
13     }
14 }
15 int find(int x)  //一直找到父亲节点
16 {
17     while(x != pre[x])
18         x=pre[x];
19     return x;
20 }
21 int unit(int x,int y) // x,y合并
22 {
23     if(x==y)return 0;  
24     if(num[x]>num[y]) //谁的集合元素多合并在谁的目录下,这样才能找到传染最多的人
25     {
26         pre[y]=x;    //y归x管(父亲节点为y的集合赋值为父亲节点x);
27         num[x]+=num[y]; // 个数合并
28     }
29     else 
30     {
31         pre[x]=y;
32         num[y]+=num[x];
33     }
34     return 0;
35 }
36 int main()
37 {
38     int n,m,k,a,b,x,y;
39     while(scanf("%d%d",&n,&m) != EOF)
40     {
41         if(n==0 && m==0)
42             break;
43         Input();
44         for(int j=0;j<m;j++)
45         {
46             scanf("%d",&k);
47             scanf("%d",&a);
48             for(int i=1;i<k;i++)
49             {
50                 scanf("%d",&b);
51                 x=find(a);
52                 y=find(b);
53                 unit(x,y); //合并。
54             }
55         }
56         printf("%d\n",num[find(0)]);
57     }
58     return 0;
59 }

 

posted on 2013-08-20 10:18  随风浪子的博客  阅读(122)  评论(0编辑  收藏  举报

导航