题目描述:
背景
霍珀教授正在研究一种稀有昆虫的性行为。他假设它们有两种不同的性别,而且它们只与异性昆虫互动。在他的实验中,单个的虫子及其相互作用很容易识别,因为它们的背上印着数字。
问题
给定一个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;
}