POJ 1611 The Suspects(并查集)

经典的并查集题目。著名的非典问题 = = 。PS:最近H7N9也挺厉害的。各位小心


#include <cstdio>

using namespace std;

int father[30005],num[30005];

int main()
{
    void Init_set(int x);
    int  Find_set(int x);
    void Union_set(int a,int b);
    int n,m;
    int count,first,b;
    while(scanf("%d %d",&n,&m)!=EOF && n!=0)
    {
        Init_set(n);
        while(m--)
        {
            scanf("%d %d",&count,&first);
            for(int j=1;j<count;j++)
            {
                scanf("%d",&b);
                Union_set(first,b); 
            }
        }
        printf("%d\n",num[Find_set(0)]);
    }
    return 0;
}

void Init_set(int x)   //初始化
{
    for(int i=0;i<x;i++)
    {
        father[i]=i;
        num[i]=1;
    }
}

int Find_set(int x)   
{
    if(father[x]!=x)
    {
        father[x]=Find_set(father[x]);
    }
    return father[x];
}

void Union_set(int a,int b)   //将所有的点都并到同一个根上。
{
    int x=Find_set(a);
    int y=Find_set(b);
    if(x==y)
    {
        return;
    }
    if(num[x]<=num[y])   //记录根上的点的数目。
    {
        father[x] = y;
        num[y]+=num[x];
    }
    else
    {
        father[y]=x;
        num[x]+=num[y];
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值