PPOJ 2492 A Bug's Life(分层并查集)

题目链接:
POJ 2492 A Bug’s Life
题意:
有n个昆虫,一般只有性别相异的昆虫才可配对,如果是一只同性恋昆虫,那么它和同性、异性均可配对。
现在给出m组配对关系,问这n个昆虫中是否含有同性恋昆虫?
分析:
由于不知道每只昆虫的性别,那么可以把两种情况都考虑。第i只昆虫性别的反面用i+n表示,
那么对于每对昆虫a,b,要把a和b+n以及a+n和b分别放在同一集合。
当发现a和a+n或者b和b+n同一个集合是那么就出现了同性恋昆虫。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

const int maxn=2010;

int pre[maxn*2],T,n,m,a,b,cases=0;

int find(int x)
{
    return pre[x]==x?x:pre[x]=find(pre[x]);
}

void mix(int x,int y)
{
    int fx=find(x);
    int fy=find(y);
    if(fx!=fy)
    {
        pre[fx]=fy;
    }
}

int main()
{
#ifdef LOCAL
    freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
#endif
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        for(int i=0;i<=2*n;i++)
            pre[i]=i;
        int ok=0;
        for(int i=1;i<=m;i++)
        {
            scanf("%d%d",&a,&b);
            if(ok) continue;
            mix(a,b+n);
            mix(a+n,b);
            if(find(a)==find(a+n)||find(b)==find(b+n)) ok=1;
        }
        printf("Scenario #%d:\n",++cases);
        if(ok) printf("Suspicious bugs found!\n");
        else printf("No suspicious bugs found!\n");
        if(T) printf("\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值