poj1703 Find them, Catch them(并查集)

每次给的关系表示两个物品不属于同一集合,题目关键在于一共只有两个集合,那就设一个对立关键字好了,表示两个物品对立,每次给一个对立关系u,v,就把(u和v的对立)与(v和u的对立)并起来,最后査就好了。


#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<stack>
#include<cstring>
#include<map>
#include<string>
#include<climits>

#define maxn 110000
using namespace std;

int father[maxn];
int opp[maxn];
int _find(int x)
{
	int t=x;
	while(x!=father[x])
		x=father[x];
	while(t!=father[t])
	{
		int temp=t;
		t=father[t];
		father[temp]=x;
	}
	return x;
}

bool join(int x,int y)
{
	x=_find(x);
	y=_find(y);
	if(x!=y)
	{
		father[x]=y;
		return true;
	}
	return false;
}


int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		int n,m;
		scanf("%d%d",&n,&m);
		for(int i=0;i<=n;++i)
		{
			father[i]=i;
			opp[i]=-1;
		}
		for(int i=0;i<m;++i)
		{
			char op[10];
			int u,v;
			scanf("%s%d%d",op,&u,&v);
			if(op[0]=='D')
			{
				if(opp[u]==opp[v] && opp[u]==-1)
				{
					opp[u]=v;
					opp[v]=u;
				}
				else if(opp[u]==-1)
				{
					opp[u]=v;
					join(u,opp[v]);
				}
				else if(opp[v]==-1)
				{
					opp[v]=u;
					join(v,opp[u]);
				}
				else
				{
					join(u,opp[v]);
					join(v,opp[u]);
				}
			}
			else
			{
				if(_find(u)== _find(v))
					printf("In the same gang.\n");
				else if(_find(u)==_find(opp[v]))
                                        printf("In different gangs.\n");
				else
					printf("Not sure yet.\n");
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值