How Many Tables HDU - 1213 基础并查集

题意

给定 n , m,分别代表人数和团体数,后面m行每行的一个数代表这个团体的人数。0被怀疑可能患有非典,与被怀疑患有非典的人在同一团体的人也被怀疑可能患有非典,被怀疑患有非典的人都需要隔离以防万一,请输出需要隔离多少人。

最后只需输出与0在同一树中的结点数即可

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=30005;
int pre[maxn];
int cnt[maxn];    //记录该集合中元素的个数  只对根节点有效
int s[maxn];
int find(int x)
{
   if(pre[x]==x)
        return x;
   else
    return pre[x]=find(pre[x]);
}
void join(int x,int y)
{
    x=find(x),y=find(y);
    if(x!=y)
    {
        cnt[x]+=cnt[y];
        pre[y]=x;
    }
}
int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m)&&(m||n))
    {
        for(int i=0;i<n;i++)
        {
            pre[i]=i;
            cnt[i]=1;
        }
        for(int i=0;i<m;i++)
        {
            int a;
            scanf("%d",&a);
            for(int j=0;j<a;j++)
                scanf("%d",&s[j]);
            for(int j=1;j<a;j++)
                join(s[0],s[j]);
        }
        printf("%d\n",cnt[find(0)]);   
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41837216/article/details/82954561