HDU1829 - A Bug's Life 分组并查集

22 篇文章 0 订阅
9 篇文章 0 订阅

HDU1829 - A Bug's Life : http://acm.hdu.edu.cn/showproblem.php?pid=1829

题意:首先输入T,接下来是T组测试数据。每组测试数据第一行输入N,M代表共有N个人,接下来有M行输入.每行有两个数a和b,代表编号为a和b的两个人是异性。输入结束后判断是否存在错误的信息。如N = 3,M = 3,接下来是3组输入。1  2,2  3,1  3。此组数据是错的,因为1 和 3都和2是异性,说明1 和 3是同性,但第三组数据又说1和3是异性。所以错了,输出“Suspicious bugs found!”,若没错则输出“No suspicious bugs found!”.这里输出的是主要信息,其他格式不赘述。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 2010;
int Father[MAXN],flag;
int T,N,M;
int x,y;
int Case = 0;
void Initial()
{
	for(int i = 0;i < MAXN*2 + 5;i++)
		Father[i] = i;
	flag = 0;
}
int Find(int x)
{
	if(x == Father[x])return x;
	return Father[x] = Find(Father[x]); 
	//return x == Father[x] ? x : Find(Father[x]);
}
void Union(int x,int y)
{
	x = Find(x);
	y = Find(y);
	if(x != y)
		Father[x] = y;
}
bool Same(int x,int y)
{
	return Find(x) == Find(y);
}
int main()
{
	scanf("%d",&T);
	while(T--)
	{
		Initial();
		scanf("%d%d",&N,&M);
		for(int i = 0;i < M;i++)
		{
			scanf("%d%d",&x,&y);
			if(flag)continue;
			if(Same(x,y))flag = 1;//判断x,y是否是同性,若输入没错,则输入的是一对异性 
			// 1 - N 表示的是男性,N + 1 表示的是女性 
			Union(x,y+N);//若x是男性,则y一定是女性 
			Union(x+N,y);//若x是女性,则y一定是男性 
		}
		printf("Scenario #%d:\n",++Case);
		if(flag)printf("Suspicious bugs found!\n\n");
		else printf("No suspicious bugs found!\n\n");
	}
	return 0;
}
PS:此题是POJ上题名为"食物链"的简化版本,有兴趣的可以去做做这题,思路是一样的.



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值