POJ 2492 A Bug's Life

题目描述:

 

背景

霍珀教授正在研究一种稀有昆虫的性行为。他假设它们有两种不同的性别,而且它们只与异性昆虫互动。在他的实验中,单个的虫子及其相互作用很容易识别,因为它们的背上印着数字。

问题

给定一个bug交互列表,判断这个实验是否支持他的假设,即没有同性恋bug的两种性别,还是包含一些错误的bug交互。

Sample Input

2
3 3
1 2
2 3
1 3
4 2
1 2
3 4

Sample Output

Scenario #1:
Suspicious bugs found!

Scenario #2:
No suspicious bugs found!

 

带权并查集。虫子之间存在两种关系,同性或异性。用value为1表示异性,value为0表示同性。用求模运算来表示权值更新和判断即可。

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <queue>
#include <algorithm>
#include <string.h>

using namespace std;

int n,t,d,x,y,flag;
int tree[2010];
int value[2010];

int find(int x){
    int tmp=x;
    while(tmp!=tree[tmp]){
        tmp=tree[tmp];
        value[x]=(value[x]+value[tmp])%2;
    }
    return tree[x]=tmp;
}

int main()
{
    scanf("%d",&t);
    for(int k=1;k<=t;k++){
        printf("Scenario #%d:\n",k);
        scanf("%d%d",&n,&d);

        flag=0;
        memset(value,0,sizeof(value));
        for(int i=0;i<=n;i++){
            tree[i]=i;
        }

        while(d--){
            scanf("%d%d",&x,&y);
            int rx=find(x);
            int ry=find(y);
            if(rx!=ry){
                tree[ry]=rx;
                value[ry]=(value[x]+value[y]+1)%2;
            }
            else {
                if((value[x]+value[y])%2==0)flag=1;
            }
        }
        printf(flag?"Suspicious bugs found!\n":"No suspicious bugs found!\n");
        if(k!=t)printf("\n");
    }
    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值