poj 1703 Find them, Catch them (并查集)

点击打开链接
#include"stdio.h"
int f[100005];
int r[100005];
void set(int n)
{
	int i;
	for(i=1;i<=n;i++)
	{
		f[i]=i;r[i]=0;
	}
}
int find(int x)
{
	int t;
	if(x!=f[x])
	{
		t=f[x];
		f[x]=find(f[x]);
		r[x]=(r[x]+r[t])%2;
	}
	return f[x];
}
void Union(int x,int y)
{
	int xx,yy;
	xx=find(x);
	yy=find(y);
	f[xx]=yy;
	r[xx]=(r[x]+r[y])^1;
}
int main()
{
	int a,b,t,n,m,aa,bb;
	char s[3];
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d",&n,&m);
		set(n);
		while(m--)
		{
			scanf("%s%d%d",s,&a,&b);
			if(s[0]=='A')
			{
				aa=find(a);bb=find(b);
				if(aa==bb&&r[a]!=r[b])
					printf("In different gangs.\n");
				else if(aa==bb&&r[a]==r[b])
					printf("In the same gang.\n");
				else
					printf("Not sure yet.\n");
			}
			else Union(a,b);
		}
	}
	return 0;
}


posted on 2012-07-31 07:59  Slege  阅读(78)  评论(0编辑  收藏  举报

导航