hdoj--1829--A Bug's Life(带权并查集)

A Bug's Life

Time Limit: 15000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 12677    Accepted Submission(s): 4142

Problem 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
 

Recommend
linle   |   We have carefully selected several similar problems for you:  1558 1811 1198 1856 1325 

//题意:给出了1--n的m种关系,x--y中x跟y的性别未知,问有没有可能出现同性恋
//一道带权并查集问题, 不要考虑x,y的性别是男是女,只需要考虑他们的性别
//是否一致, vis数组存放爱人的性别,
//举例子:x--y说明x和y有关系 
//如果说vis[x]不为零说明x有了爱人,并且vis[x]存放的就是他爱人的性别,
//那么 那么y一定跟vis[x]是一个集合中的,不需要管vis存放的都是什么数字 
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define MAXN 10000010
int n,m,flag;
int vis[MAXN],pre[MAXN];
void init()
{
	for(int i=0;i<=n;i++)
	{
		vis[i]=0;
		pre[i]=i;
	}
}
int find(int x)
{
	if(pre[x]!=x)
	pre[x]=find(pre[x]);
	return pre[x];
}
void join(int x,int y)
{
	int fx=find(x);
	int fy=find(y);
	if(fx==fy)
		flag=1;
	else
	{
		if(vis[fx])//如果说fx已经有了爱人,那么fy的性别一定要和fx性别一样 
			pre[vis[fx]]=fy;
		if(vis[fy])
			pre[vis[fy]]=fx; 
		vis[fx]=fy;vis[fy]=fx;//vis存放爱人的性别,fx爱人的性别是fy 
		//如果说两人性别不属于同一结合,两人可以相恋 
	}
}
int main()
{
	int t,k=1;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d",&n,&m);
		init();
		flag=0;
		int x,y;
		for(int i=0;i<m;i++)
		{
			scanf("%d%d",&x,&y);
			join(x,y);
		}
		printf("Scenario #%d:
",k++);
		if(flag)
			printf("Suspicious bugs found!

");
		else
			printf("No suspicious bugs found!

");
	}
	return 0;
}


原文地址:https://www.cnblogs.com/playboy307/p/5273493.html