A Bug’s Life
Background
Professor Hopper is researching the sexual behavior of a rare species of bugs. He assumes that they feature two different genders and that they only interact with bugs of the opposite gender. In his experiment, individual bugs and their interactions were easy to identify, because numbers were printed on their backs.
Problem
Given a list of bug interactions, decide whether the experiment supports his assumption of two genders with no homosexual bugs or if it contains some bug interactions that falsify it.
Input
The first line of the input contains the number of scenarios. Each scenario starts with one line giving the number of bugs (at least one, and up to 2000) and the number of interactions (up to 1000000) separated by a single space. In the following lines, each interaction is given in the form of two distinct bug numbers separated by a single space. Bugs are numbered consecutively starting from one.
Output
The output for every scenario is a line containing “Scenario #i:”, where i is the number of the scenario starting at 1, followed by one line saying either “No suspicious bugs found!” if the experiment is consistent with his assumption about the bugs’ sexual behavior, or “Suspicious bugs found!” if Professor Hopper’s assumption is definitely wrong.
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!
Hint
Huge input,scanf is recommended.
题目大意:
给定昆虫数量和交配次数,每条交配记录由两个昆虫编号组成。问是否存在同性恋?
思路:
这个题模拟可做,这里用并查集实现了一下。只是这个并查集思路略有不同,我们可以开两个并查集。每次我们将前面的昆虫和与它交配昆虫的“对立昆虫”(在代码中表示为x+MAXN)放在同一个集合中,反过来也是一样。首先判断输入是否在同一个集合,若是,则存在同性恋。
坑点
初始化数组和最后的输出,要多输出一个换行。
代码如下:
#include<iostream>
#include<cstdio>
using namespace std;
const int MAXN=2010;//建立两个并查集
int bug[2*MAXN+10];
void init(int number)//初始化
{
for(int j=1;j<=number;j++)bug[j]=j;
}
int getf(int v)
{
if(v==bug[v])return v;
else return bug[v]=getf(bug[v]);
}
void merge(int a,int b)
{
int ta=getf(a),tb=getf(b);
if(ta!=tb)
bug[tb]=ta;
}
int main()
{
int n,cnt=1;
scanf("%d",&n);
while(n--)
{
int number,interaction;
scanf("%d %d",&number,&interaction);
init(number+MAXN);//参数的大小要注意
bool flag=false;
for(int i=1;i<=interaction;i++)
{
int a,b;
scanf("%d %d",&a,&b);
if(getf(a)==getf(b))//出现了同性恋
{
flag=true;
continue;
}
merge(a,b+MAXN);//a和b+MAXN放在一个集合中
merge(b,a+MAXN);//同时b和a+MAXN放在一个集合中
}
cout<<"Scenario #"<<cnt++<<":"<<endl;
if(flag)cout<<"Suspicious bugs found!"<<endl;
else cout<<"No suspicious bugs found!"<<endl;
cout<<endl;//要多输出一个换行,这里要注意一下
}
}