POJ 2492 并查集

题意:调查一种虫子的性行为,先假定虫子里没有同性恋。每一次测试输入N只虫,然后输入M个数对( x, y ),表示 x, y 之间有性行为, 最后判断假设成立与否(即判断有没有同性恋)。

#include <iostream>
using namespace std;

#define N 1000005
int opp[N], father[N], rank[N];

void make_set ( int x )
{
	for ( int i = 0; i <= x; ++i )
	{
		father[i] = i;
		opp[i] = rank[i] = 0;
	}
}

int find_set ( int x )
{
	if ( father[x] != x )
		father[x] = find_set(father[x]);
	return father[x];
}

void Union ( int x, int y )
{
	int fx = find_set(x);
	int fy = find_set(y);
	if ( fx == fy ) return;
	if ( rank[fx] > rank[fy] )
		father[fy] = fx;
	else
		father[fx] = fy;
	if ( rank[fx] == rank[fy] )
		rank[fy]++;
}

int main()
{
	int t, n, m, x, y;
	bool find;
	scanf("%d",&t);
	for ( int i = 1; i <= t; ++i )
	{
		find = false;
		scanf("%d%d",&n,&m);
		make_set(n);
		while ( m-- )
		{
			scanf("%d%d",&x,&y);
			if ( find == false )
			{
				if ( opp[x] == 0 && opp[y] == 0 )
				{
					opp[x] = y;
					opp[y] = x;
				}
				else if ( opp[x] != 0 && opp[y] == 0 )
				{
					opp[y] = x;
					Union(y,opp[x]);
				}
				else if ( opp[x] == 0 && opp[y] != 0 )
				{
					opp[x] = y;
					Union(x,opp[y]);
				}
				else if ( opp[x] != 0 && opp[y] != 0 )
				{
					if ( find_set(x) == find_set(y) )
						find = true;
					Union(x,opp[y]);
					Union(y,opp[x]);
				}
			}
		}
		printf("Scenario #%d:\n",i);
		if ( find )
			printf("Suspicious bugs found!\n");
		else
			printf("No suspicious bugs found!\n");
		if ( i != t ) putchar('\n');
	}
	return 0;
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值