老样子,经典的并查集题目,和Find them,catch them几乎一样的做法,只不过增加了一个判断,在两个结点的父节点相同的时候判断一下他们俩的新关系和原有的关系是否有矛盾;
另外注意即使有矛盾也不能提前跳出循环,因为还有很多数据要输入= =
#include <iostream>
#include <cstdio>
#include <memory.h>
using namespace std;
#define maxn 2050
struct node{
int fa;
int re;
};
node bugs[maxn]={0};
int findfa(int a){
if(bugs[a].fa == a)
return a;
int temp = bugs[a].fa;
bugs[a].fa = findfa(temp);
bugs[a].re ^= bugs[temp].re;
return bugs[a].fa;
}
bool insert(int arg1,int arg2){
int fa1 = findfa(arg1);
int fa2 = findfa(arg2);
if(fa1 != fa2){
bugs[fa2].fa = fa1;
bugs[fa2].re = !(bugs[arg1].re^bugs[arg2].re);
return true;
}
else{
if(bugs[arg1].re == bugs[arg2].re){
return false;
}
else
return true;
}
}
int main(){
int t;
scanf("%d",&t);
for(int j=1;j<=t;++j){
int n,m;
memset(bugs,0,sizeof(bugs));
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i){
bugs[i].fa = i;
}
bool found = false;
while(m--){
int arg1,arg2;
scanf("%d%d",&arg1,&arg2);
if(!found && !insert(arg1,arg2)){
found = true;
}
}
printf("Scenario #%d:\n",j);
if(!found){
printf("No suspicious bugs found!\n\n");
}
else{
printf("Suspicious bugs found!\n\n");
}
}
//system("pause");
return 0;
}