链接:http://acm.hdu.edu.cn/showproblem.php?pid=1829
题意:判断一些类似男女配对数据里是否存在同性恋,用并查集判断是否存在同性恋,即同一集合里面是同性的人,增加辅助数组判断性别.
Ac code:
#include<iostream>
#include<cstring>
using namespace std;
#define NUM 10005
int father[NUM],sex[NUM];
void Init()
{
for(int i=0;i<NUM;++i)
{
father[i]=i;
sex[i]=0;
}
}
int findfather(int n)
{
while(n!=father[n]) n=father[n];
return father[n];
}
void Union(int a,int b)
{
int x=findfather(a);
int y=findfather(b);
if(x==y) return;
father[y]=x;
}
int main()
{
int test,p,q,x,y,flag,j=1;
cin>>test;
while(test--)
{
memset(sex,0,sizeof(sex));
Init();
flag=1;
cin>>p>>q;
for(int i=0;i<q;++i)
{
cin>>x>>y;
if(findfather(x)==findfather(y)) { flag=0;continue; }
if(sex[x]==0)
sex[x]=y; //异性
else
Union(sex[x],y); //合并同性
if(sex[y]==0)
sex[y]=x;
else
Union(x,sex[y]);
}
cout<<"Scenario #"<<j<<":"<<endl;
if(flag)
cout<<"No suspicious bugs found!"<<endl;
else
cout<<"Suspicious bugs found!"<<endl;
j++;
cout<<endl;
}
}