题目:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=86955#problem/B
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.
告诉昆虫的个数和交配数,问是否有同性恋的存在。比如:
3 3
1 2
2 3
1 3
1喜欢2,2喜欢3,1喜欢3,那么1和3就是同性恋。
运用带权并查集解决此问题。带权并查集将有关系的个体归于一类(喜欢,被喜欢,间接喜欢,间接被喜欢都属于此类),然后再进行细分,通常用关系向量表示他们的联系(往往另设一个数组)。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N=2000+5;
int father[N],prank[N];
bool flag;
int find(int a){
if(father[a]==0){
return a;
}
int temp=father[a];
father[a]=find(father[a]); //压缩路径
prank[a]=(prank[a]+prank[temp])%2; //维护关系
return father[a];
}
void init(int sc){
memset(prank,0,sizeof(prank));
memset(father,0,sizeof(father));
}
int main()
{
//freopen("cin.txt","r",stdin);
int t;
cin>>t;
for(int k=1;k<=t;k++){
int num,opera;
flag=1;
scanf("%d%d",&num,&opera);
init(num);
for(int i=0;i<opera;i++){
int a,b;
scanf("%d%d",&a,&b);
if(flag==0)continue;
int fa,fb;
fa=find(a);
fb=find(b);
if(fa!=fb){
father[fa]=fb;
prank[fa]=(prank[a]+prank[b]+1)%2; //*******
}
else {
if(prank[a]==prank[b])flag=0;
}
}
printf("Scenario #%d:\n",k);
if(flag==0)printf("Suspicious bugs found!\n\n");
else printf("No suspicious bugs found!\n\n");
}
return 0;
}
下图中的rank就是代码中的prank(因为关键字的关系后来改的)