A Bug's Life
Time Limit: 10000MS | Memory Limit: 65536K |
Total Submissions: 21871 | Accepted: 7142 |
题目链接:http://poj.org/problem?id=2492
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 interactwith bugs of the opposite gender. In his experiment, individual bugs and theirinteractions were easy to identify, because numbers were printed on theirbacks.
Problem
Given a list of bug interactions, decide whether the experiment supports hisassumption of two genders with no homosexual bugs or if it contains some buginteractions that falsify it.
Input
The first line ofthe input contains the number of scenarios. Each scenario starts with one linegiving the number of bugs (at least one, and up to 2000) and the number ofinteractions (up to 1000000) separated by a single space. In the followinglines, each interaction is given in the form of two distinct bug numbersseparated by a single space. Bugs are numbered consecutively starting from one.
Output
The output forevery scenario is a line containing "Scenario #i:", where i is thenumber of the scenario starting at 1, followed by one line saying either"No suspicious bugs found!" if the experiment is consistent with hisassumption about the bugs' sexual behavior, or "Suspicious bugsfound!" 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,scanfis recommended.
Source
TUDProgramming Contest 2005, Darmstadt, Germany
解题思路:
设置两个数组sex,set分别表示性别和祖先,利用并查集,当两者属于不同祖先,那么合并成同一个祖先,并且设置两者为不同性别,如果两者有相同祖先,那么判断两者的性别是否有冲突。
代码:
#include <iostream>
#include<cstdio>
#include<cstring>
#define maxn 2012
using namespace std;
int set[maxn];
int sex[maxn];//表示性别
int n,m;
int flag;
void init()
{
for(int i=1;i<=n;i++)
{
set[i]=i;
sex[i]=0;//初始每只bug性别都是0
}
flag=0;
}
int findSet(int x)
{
if(set[x]==x)
{
return x;
}
return set[x]=findSet(set[x]);
}
void unionSet(int a,int b)
{
int x=findSet(a);
int y=findSet(b);
if(x==y)
{
if(sex[a]==sex[b])//在一个集合中,如果a,b是同性
flag=1;
}
if(x!=y)//如果a和b没有共同的祖先,合并
{
if(x<y)
{
sex[b]=sex[a]*(-1)+1;//将b的性置为与a相反
set[y]=x;//把x的祖先合并到y的祖先
}
else
{
sex[a]=sex[b]*(-1)+1;
set[x]=y;//把x的祖先合并到y的祖先
}
}
}
int main()
{
int ts;
int a,b;
scanf("%d",&ts);
for(int i=1;i<=ts;i++)
{
scanf("%d%d",&n,&m);
init();
while(m--)
{
scanf("%d%d",&a,&b);
if(flag==0)
unionSet(a,b);
}
if(flag==1)
{
printf("Scenario #%d:\nSuspicious bugs found!\n\n",i);
}
else
{
printf("Scenario #%d:\nNo suspicious bugs found!\n\n",i);
}
}
return 0;
}