您的位置:首页 > 其它

POJ 1611 The Suspects(并查集)

2016-03-01 17:02 351 查看
Description

有n名学生(编号0~n-1)分成了m组,其中学生0感染了病毒,这种病毒极易传播,两人只要接触就会传播,一人感染全组感染,问共有多少名学生会感染这种病毒?

Input

多组用例,每组用例第一行为两个整数n和m表示学生人数和组数,之后m行每行首先输入该组学生人数num,然后输入num个整数表示该组学生的编号,以 0 0结束输入

Output

对于每组用例,输出被感染学生的数量

Sample Input

100 4

2 1 2

5 10 13 11 12 14

2 0 1

2 99 2

200 2

1 5

5 1 2 3 4 5

1 0

0 0

Sample Output

4

1

1

Solution

并查集,用num[i]表示每个集合的元素数量,在合并过程中加上num的累加过程,最后答案即为num[find(0)]

Code

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
#define maxn 33333
int fa[maxn];
int deep[maxn];
int num[maxn];
void init(int n)
{
for(int i=0;i<=n;i++)
{
fa[i]=i;
deep[i]=0;
num[i]=1;
}
}
int find(int x)
{
if(fa[x]==x) return x;
else return fa[x]=find(fa[x]);
}
void unite(int x,int y)
{
x=find(x);
y=find(y);
if(x==y) return;
if(deep[x]<deep[y]) fa[x]=y,num[y]+=num[x];
else
{
fa[y]=x,num[x]+=num[y];
if(deep[x]==deep[y]) deep[x]++;
}
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m),n||m)
{
init(n);
for(int i=0;i<m;i++)
{
int cnt,pre,last;
scanf("%d",&cnt);
if(cnt)scanf("%d",&pre);
if(cnt>1)
for(int j=1;j<cnt;j++)
{
scanf("%d",&last);
unite(pre,last);
pre=last;
}
}
printf("%d\n",num[find(0)]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: