您的位置:首页 > 其它

hdu-1829 & poj-2492 并查集

2015-01-19 11:00 483 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1829

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <iomanip>

using namespace std;

int t, n, m;
int fa[2200];
int sex[2200];//sex[i]=j 表示i与j性别相反
int a, b;
int ok;

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

void un(int x, int y)
{
	int fx = findd(x);
	int fy = findd(y);

	if (fx == fy)//同性的
	{
		return;
	}
	else
	{
		if (fy > fx)
			fa[fy] = fx;
		else 
			fa[fx] = fy;
	}
}

int cases = 1;

int main()
{
	scanf("%d",&t);
	while (t--)
	{
		ok = 1;
		scanf("%d %d", &n, &m);
		{
			for (int i = 1; i <= n; i++)
			{
				fa[i] = i;	
			}
			memset(sex,0,sizeof(sex));

			for (int i = 1; i <= m;i++)
			{
				scanf("%d%d",&a,&b);
				if (!ok)
					continue;
				if (findd(a) == findd(b))//同性的
				{
					ok = 0;
					continue;
				}

				if (sex[a] == 0)
				{
					sex[a] = b;
				}
				else
				{
					un(sex[a], b);
				}

				if (sex[b] == 0)
				{
					sex[b] = a;
				}
				else
				{
					un(sex[b], a);
				}
			}
		}

		if (!ok)
		{
			printf("Scenario #%d:\n",cases++);
			puts("Suspicious bugs found!");
			printf("\n");
		}
		else
		{
			printf("Scenario #%d:\n",cases++);
			puts("No suspicious bugs found!");
			printf("\n");
		}
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: