【POJ】1703 - Find them, Catch them(加权并查集)

Find them, Catch them
Time Limit: 1000MS   Memory Limit: 10000KB   64bit IO Format: %I64d & %I64u

Submit Status

Description

The police office in Tadu City decides to say ends to the chaos, as launch actions to root up the TWO gangs in the city, Gang Dragon and Gang Snake. However, the police first needs to identify which gang a criminal belongs to. The present question is, given two criminals; do they belong to a same clan? You must give your judgment based on incomplete information. (Since the gangsters are always acting secretly.) 

Assume N (N <= 10^5) criminals are currently in Tadu City, numbered from 1 to N. And of course, at least one of them belongs to Gang Dragon, and the same for Gang Snake. You will be given M (M <= 10^5) messages in sequence, which are in the following two kinds: 

1. D [a] [b] 
where [a] and [b] are the numbers of two criminals, and they belong to different gangs. 

2. A [a] [b] 
where [a] and [b] are the numbers of two criminals. This requires you to decide whether a and b belong to a same gang. 

Input

The first line of the input contains a single integer T (1 <= T <= 20), the number of test cases. Then T cases follow. Each test case begins with a line with two integers N and M, followed by M lines each containing one message as described above.

Output

For each message "A [a] [b]" in each case, your program should give the judgment based on the information got before. The answers might be one of "In the same gang.", "In different gangs." and "Not sure yet."

Sample Input

1
5 5
A 1 2
D 1 2
A 1 2
D 2 4
A 1 4

Sample Output

Not sure yet.
In different gangs.
In the same gang.

Source

POJ Monthly--2004.07.18


还是用的加权并查集的做法,其节点的权值为关系:0为同类,1为异类。如果根结点不同表示还没有合并,就进行合并处理,如果根结点相同可以不处理。

此用法个人感觉和向量、补码的用法是差不多的,看个人理解吧。

代码如下:

#include <cstdio>
#include <cstring>
int f[111111],re[111111];		//re数组表示与其父节点的关系,1为不同类,0为同类
int find(int x)
{
	if (x!=f[x])
	{
		int t;
		t=f[x];
		f[x]=find(f[x]);
		re[x]=(re[x]+re[t])%2;
	}
	return f[x];
}
int main()
{
	int u;
	int n,m;		//n为总数,m为描述的个数
	scanf ("%d",&u);
	while (u--)
	{
		scanf ("%d %d",&n,&m);
		for (int i=1;i<=n;i++)
			f[i]=i;
		memset(re,0,sizeof(re));
		getchar();		//吸收换行符 
		char op;		//将要进行的操作 
		int x,y;
		while (m--)
		{
			scanf ("%c %d %d",&op,&x,&y);
			getchar();
			int fx,fy;
			fx=find(x);
			fy=find(y);
			if (op=='D')
			{
				if (fx!=fy)		//如果根结点不同的话需要合并整理
				{
					f[fy]=fx;
					re[fy]=(2-re[y]+re[x]+1)%2;
				}
			}
			else
			{
				if (fx!=fy)
					printf ("Not sure yet.");
				else
				{
					int ans;
					ans=(2-re[y]+re[x])%2;
					if (ans)
						printf ("In different gangs.");
					else
						printf ("In the same gang.");
				}
				printf ("\n");
			}
		}
	}
	return 0;
} 


你可能感兴趣的:(【POJ】1703 - Find them, Catch them(加权并查集))