A Bug’s Life
Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 16894 Accepted Submission(s): 5405
Problem Description
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.
题意:
假设某种细菌有性别,现在给出一些细菌之间的关系,问是否存在同性行为。
思路:
怎样从给出的关系里判断存不存在同性行为呢?假设A与B和C都发生了性行为,而B和C又发生了性行为,那么肯定就存在同性行为。思路再拓展一下,就是找是否存在奇环。
判断是否有奇环存在的方法:
任选一点建树,若存在深度为2的倍数的返祖边,则存在奇环。
代码如下:
#include<stdio.h>
#include<queue>
#define maxn 2005
#define ll long long
using namespace std;
bool mapp[maxn][maxn];
bool app[maxn];
ll n,m;
int casenum=0;
void solve()
{
queue<int> q;
int mark[maxn];
int i,j;
for(i=1;i<=n;i++)
mark[i]=-1;
for(i=1;i<=n;i++)
{
if(app[i])
{
q.push(i);
mark[i]=0;
break;
}
}
while(!q.empty())
{
int now=q.front();
q.pop();
for(i=1;i<=n;i++)
{
if(mapp[i][now])
{
if(mark[i]!=-1)
{
if((mark[now]-mark[i])%2==0)
{
printf("Scenario #%d:\nSuspicious bugs found!\n\n",casenum);
return ;
}
continue;
}
q.push(i);
mark[i]=mark[now]+1;
}
}
if(q.empty())
{
for(i=1;i<=n;i++)
{
if(mark[i]!=-1) continue;
if(app[i])
{
q.push(i);
mark[i]=0;
break;
}
}
}
}
printf("Scenario #%d:\nNo suspicious bugs found!\n\n",casenum);
}
int main()
{
int t;
scanf("%d",&t);
for(casenum=1;casenum<=t;casenum++)
{
scanf("%lld %lld",&n,&m);
ll i,j;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
mapp[i][j]=0;
for(i=0;i<m;i++)
{
int a,b;
scanf("%d %d",&a,&b);
app[a]=1;app[b]=1;
mapp[a][b]=mapp[b][a]=1;
}
solve();
}
}