【POJ】2492 - A Bug's Life(带权并查集)

A Bug's Life
Time Limit:10000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit  Status

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.


其实这种分类的并查集的题可以不用权来做,这样会耗费一点时间,但是既然学到这了,那就还用这个吧。

这道题的输出格式好坑爹,本来还以为要考虑最后一组数据不多加一个换行符的问题,结果PE了。后来才发现输出的时候两个换行符就可以AC了。

代码如下:

#include <cstdio>
#include <cstring>
int f[1111111],re[1111111];		//re数组表示与其父节点的关系,1为不同性,0为同性 
int find(int x)
{
	if (x!=f[x])
	{
		int t;
		t=f[x];
		f[x]=find(f[x]);
		re[x]=(re[x]+re[t])%2;
	}
	return f[x];
}
int main()
{
	int u;
	int n,m;		//n为总数,m为描述的个数
	int num=1;
	bool flag;
	scanf ("%d",&u);
	while (u--)
	{
		scanf ("%d %d",&n,&m);
		for (int i=1;i<=n;i++)
			f[i]=i;
		memset(re,0,sizeof(re));
		flag=false;
		int x,y;
		while (m--)
		{
			scanf ("%d %d",&x,&y);
			int fx,fy;
			fx=find(x);
			fy=find(y);
			if (fx!=fy)		//如果根结点不同的话需要合并整理
			{
				f[fy]=fx;
				re[fy]=(2-re[y]+re[x]+1)%2;
			}
			else
			{
				if (re[x]==re[y])
					flag=true;
			}
		}
		printf ("Scenario #%d:\n",num++);
		if (flag)
			printf ("Suspicious bugs found!\n\n");
		else
			printf ("No suspicious bugs found!\n\n");
	}
	return 0;
}


你可能感兴趣的:(【POJ】2492 - A Bug's Life(带权并查集))