POJ2492 A Bug's Life【种类并查集】

A Bug's Life

Time Limit: 10000MS   Memory Limit: 65536K
Total Submissions: 45450   Accepted: 14666

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

问题链接:POJ2492 A Bug's Life

问题描述:有N只虫(从1开始编号),a b表示虫子a和虫子b发生关系,问是否存在同性恋的关系,存在输出 Suspicious bugs found!,否则输出 No suspicious bugs found!

解题思路:种类并查集,pre存储i的父节点 r存储i和父节点的关系,0表示i和父节点是同性,1表示是异性 。对find函数和join函数的修改看代码

AC的C++程序:

#include

using namespace std;

const int N=2010;

int pre[N],r[N];//pre存储i的父节点 r存储i和父节点的关系,0表示i和父节点是同性,1表示是异性 
void init(int n)
{
	for(int i=0;i<=n;i++){
		pre[i]=i;//自己为自己的父节点 
		r[i]=0;//自己与自己是同性 
	}
}

int find(int x)
{
	if(x!=pre[x]){
		int rt=pre[x];
		pre[x]=find(rt);
		r[x]^=r[rt];
	}
	return pre[x];
}

bool join(int x,int y)
{
	int fx=find(x);
	int fy=find(y);
	if(fx!=fy){//fx和fy是两颗树,合并 
		pre[fy]=fx;
		r[fy]=1^r[x]^r[y];//求fy和其父节点fx的关系:y和fy的关系是r[y],y和x的关系是1,x和fx的关系是r[x], 
	}
	else{
		if(r[x]==r[y])
		  return true;
	}
	return false;
}

int main()
{
	int n,m,T,a,b,x;
	char c;
	scanf("%d",&T);
	for(int t=1;t<=T;t++){
		scanf("%d%d",&n,&m);
		init(n);
		bool flag=false;
		while(m--){
			scanf("%d%d",&a,&b);
			if(join(a,b))
			  flag=true;
		}
		printf("Scenario #%d:\n",t);
		if(flag)
		   printf("Suspicious bugs found!\n\n");
		else
		   printf("No suspicious bugs found!\n\n");
	}
	return 0;
}

 

你可能感兴趣的:(数据结构)