POJ1703 Find them, Catch them(并查集)

本文介绍使用C++实现并查集解决食物链问题的实例,通过开多倍数组储存每种情况,实现高效查找和合并操作。

题意:

两个两个输入一些数,D代表这两个数不同,A代表查询这两个数是否相同

要点:

与食物链那一题类似,都是开多倍数组,储存每种情况


15321734Seasonal1703Accepted1680K375MSC++973B2016-03-27 18:34:06
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define maxn 100050
int p[maxn * 2], rank[maxn * 2];
int m, n;

void init()
{
	for (int i = 1; i <= 2*m; ++i)//注意这里初始化要2*m
	{
		p[i] = i;
		rank[i] = 0;
	}
}
int find(int x)
{
	if (p[x] == x) return x;
	return p[x] = find(p[x]);
}
void merge(int x, int y)
{
	x = find(x);
	y = find(y);
	if (x == y) return;
	if (rank[x] > rank[y])
		p[y] = x;
	else
	{
		p[x] = y;
		if (rank[x] == rank[y]) ++rank[y];
	}
}
bool same(int x, int y)
{
	return find(x) == find(y);
}
int main()
{
	int t,i,x,y;
	char str;
	scanf("%d", &t);
	while (t--)
	{
		scanf("%d%d", &m, &n);
		getchar();
		init();
		while(n--)
		{
			scanf("%c%d%d", &str,&x,&y);
			getchar();			//这一步比较重要,清除缓冲区
			if (str == 'A')
			{
				if (same(x, y))
					printf("In the same gang.\n");
				else if (same(x, y + m))
					printf("In different gangs.\n");
				else
					printf("Not sure yet.\n");
			}
			else
			{
				merge(x, y + m);//合并X为A,Y为B的情况
				merge(x + m, y);//合并X为B,Y为A的情况
			}
		}
	}
	return 0;
}


转载于:https://www.cnblogs.com/seasonal/p/10343807.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值