The Suspects浅析

The Suspects:
这道题是利用并查集第手法,将每一组的数据相串联,以其中最小的数作为根,再归集到0上。
最后只需要查看0的关联数目即可

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int father[30010];
int sum[30010];
int f(int x)
{
    
    
    if(x!=father[x])//根节点的n==father[n]
        father[x]=f(father[x]);
    return father[x];//或return  father[n]==n?n:father[n]=f(father[n]);
}//获取根节点
void hebing(int x,int y)
{
    
    
    int fatherx;
    int fathery;
    fatherx=f(x);//获取根节点
    fathery=f(y);//获取根节点
    if(fatherx<fathery)//使用数字小的数字合并为根节点
    {
    
    
        father[fathery]=fatherx;
        sum[fatherx]+=sum[fathery];
    }
    if(fathery<fatherx)
    {
    
    
        father[fatherx]=fathery;
        sum[fathery]+=sum[fatherx];
    }
}
int main()
{
    
    
    int n,m,t,i,j,g,e;
    while(scanf("%d %d",&n,&m)!=EOF)
    {
    
    
        for(i=0;i<=n;i++)
        {
    
    
            father[i]=i;
            sum[i]=1;
        }
        if(n==0&&m==0)
            break;
        for(j=0;j<m;j++)
        {
    
    
            scanf("%d %d",&t,&g);
            for(i=1;i<t;i++)//在前面已经定义了一个,所以需要从一开始,少输入一个
            {
    
    
                scanf("%d",&e);
                hebing(g,e);
            }
        }
        cout<<sum[0]<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/malloch/article/details/105935405