POJ 1611 The Suspects(并查集)

38 篇文章 0 订阅

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值