A Bug's Life
Time Limit: 10000MS | Memory Limit: 65536K | |
Total Submissions: 45943 | Accepted: 14825 |
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.
Source
TUD Programming Contest 2005, Darmstadt, Germany
首先,初始化的时候所有节点的父节点都是自己,sex[]都为0。又因为合并时无需路径压缩,所以根节点的gender始终为0,这是推导其他子节点关系的关键。
Find:由根节点始终为0,我们可以得到在Findt时当前节点 i 与根节点的更新公式:sex[i] = sex[i] ^ sex[ f[i] ] (^为异或). 即 i 和 f[i] 性别相同 则 i 和根节点是异性,否则 i 和根节点则为同性。
合并操作:合并x, y,找到x, y的父节点a, b,合并f[a] = b, 作为 子节点的那个父节点对根节点的关系 由sex[x] 和 sex[y]决定, 由于多加了一条边,所以sex[a] = (sex[x] + sex[y] +1)%2.(两个子节点的关系决定两个父节点的关系)
#include <cstdio>
#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int f[2002],sex[2002];
int find(int x){
if(f[x]==x)
return x;
int t=find(f[x]);
sex[x]=sex[x]^sex[f[x]];
return f[x]=t;
}
bool merge(int x,int y){
int a=find(x);
int b=find(y);
if(a==b){
if(sex[x]==sex[y]) return true;
return false;
}
f[a]=b;
//更新被归并的根节点的性别。
sex[a]=(sex[x]+sex[y]+1)%2;
return false;
}
int main(int argc, char** argv) {
int cnt;
scanf("%d",&cnt);
for(int i=1;i<=cnt;i++){
int n,m;
scanf("%d %d",&n,&m);
for(int j=1;j<=n;j++){
f[j]=j;
sex[j]=0;
}
int a,b;
bool flag=false;
while(m--){
scanf("%d %d",&a,&b);
//有同一个祖先。
if(flag)continue;
flag=merge(a,b);
}
if(flag)
printf("Scenario #%d:\nSuspicious bugs found!\n\n",i);
else
printf("Scenario #%d:\nNo suspicious bugs found!\n\n",i);
}
return 0;
}