【并查集】poj 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 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.


题意:给出几组昆虫交配的关系,最后判断这些关系中是否存在同性恋的关系。


思路:这道题是很裸的并查集的题目,思路就是每次交配的时候把两个性别的昆虫分别放入各自的集合中,开始的时候就是卡在了如何将两个类别的昆虫分别合并到两个集合中,下面给出这种合并的方法,感觉这个想法值得记录收藏一下,相关的题都可以举一反三一下。


【参考代码】

#include
#include
using namespace std;

const int Max=2005;
int p[Max];
int op[Max];
int rank[Max];

void make_set(int x)
{
	p[x]=x;
	rank[x]=0;
}

int find_set(int x)
{
	int r=x;
	while(r!=p[r]) {
		r=p[r];
	}
	return r;
}

void union_set(int x,int y)
{
	int fx=find_set(x);
	int fy=find_set(y);
	if(fx==fy) return;
	else {
		if(rank[fx]>rank[fy]) {
			p[fy]=fx;
		}
		else {
			p[fx]=fy;
			if(rank[fx]==rank[fy]) rank[fy]++;
		}
	}
}

int main()
{
	int T,num,casf,cas=0;scanf("%d",&T);
	while(T--) {
		bool judge=false;
		for(int i=0;i<=Max;i++) make_set(i);
		memset(op,0,sizeof(op));
		scanf("%d%d",&num,&casf);
		for(int i=0;i



你可能感兴趣的:(并查集)