扩展域的并查集(1)

Training 4 - C题

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 Input2

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.
#pragma warning (disable:4996)
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define inf 0X3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 2 * 2000 + 5;

int fa[maxn];

void initial(int n)
{
	for (int i = 1; i <= 2 * n; i++)
	{
		fa[i] = i;
	}
}

int get(int x)
{
	if (x == fa[x])
		return x;
	return fa[x] = get(fa[x]);
}

int main()
{
	int cas;
	scanf("%d", &cas);
	for (int i = 1; i <= cas; i++)
	{
		int n, k;
		scanf("%d%d", &n, &k);
		initial(n);
		bool flag = 0;
		while (k--)
		{
			int x, y;
			scanf("%d%d", &x, &y);
			if (get(x) == get(y))
				flag = 1;
			else
			{
				fa[get(x)] = get(y + n);
				fa[get(x + n)] = get(y);
			}
		}
		if (flag)
			printf("Scenario #%d:\nSuspicious bugs found!\n\n", i);
		else
			printf("Scenario #%d:\nNo suspicious bugs found!\n\n", i);
	}
	return 0;
}

思路:
1-n的区间表示自身,n+1-n+n的区间表示配偶
对于每两个数x和y,将x和y的配偶合并,y和x的配偶合并。判断时,判断两个数是不是同一集合即可。

发布了28 篇原创文章 · 获赞 0 · 访问量 328

猜你喜欢

转载自blog.csdn.net/xukeke12138/article/details/104732173