版权声明:小媛原创,转载请注明出处! https://blog.csdn.net/xingfushiniziji/article/details/86071346
/*为每个虫子开两个节点
分别表示该虫子为雄性和该虫子为雌性
例如1表示虫子1为雄性2表示虫子1为雌性,3表示虫子2是雄性4表示虫子2是雌性
如果数据给出了1 2交配,则合并1 4和2 3,表示1 4同时为真和2 3同时为真
依次处理,每次合并之前判断一下合并后会不会产生矛盾
*/
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=1e3*2+5;
int father[maxn],sex[maxn];
int n,m;
void init()
{
for(int i=1;i<=n;i++){
father[i]=i;
sex[i]=0;
}
}
int find(int x)
{
if(x!=father[x]){
int temp=father[x];
father[x]=find(father[x]);
sex[x]=(sex[x]+sex[temp])%2;
}
return father[x];
}
bool Union (int p,int q)
{
int a=find(p);
int b=find(q);
if(a==b&&sex[p]==sex[q]) return true;
else{
father[a]=b;
sex[a]=(sex[p]+sex[q]+1)%2;
}
return false;
}
int main()
{
int t,cns=1;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
init();//处理一下父节点,为每个虫子开俩节点
int x,y;
bool flag=false;
for(int i=1;i<=m;i++){
scanf("%d%d",&x,&y);
if(Union(x,y)) flag=true;
}
printf("Scenario #%d:\n",cns++);
if(flag) printf("Suspicious bugs found!\n\n");
else printf("No suspicious bugs found!\n\n");
}
return 0;
}
参考:https://blog.csdn.net/creat2012/article/details/20037747