Find them, Catch them

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 59152 Accepted: 17972

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.

题目意思:有两个帮派,分别是龙头帮和蛇头帮,现在有这两个帮派里面的成员n个,但是未给出具体帮派,给出询问,A x y表示x y是否在同一个帮派,是输出in same gang,不是输出 in different gangs ,不确定说出not sure not,D x y表示x y在不同帮派(这个信息给关键,能帮助我们确定根节点的信息)。
思路:先考虑D x y,表示这两个帮派一定不在同一个帮派里面,直接并起来,并且加一个关系数组用来描述当前节点与根节点的关系,1表示不同类,0表示相同类,r【fx】=(r【x】+r【y】+1)%2,这个公式很容易推,枚举结果就能得到这个公式,一开始我想出了这样一个反例:
后来发现这样其实是错误的,因为D x y是不同的类型,不可能同时为男,(这里只是用男女比喻龙头蛇头帮)。然后枚举x,y有00 01 10 11然后求出fx最后得到这个公式了。
那么D X Y 就解决了,然后我们需要考虑节点与节点之间的关系,给出一张图:


最后给出具体代码:

#include<iostream>
#include<string>
using namespace std;
const int maxn=1e5+10;
int re[maxn];//1表示不同类,0表示相同类 
int t,f[maxn];
int find(int x){
	if(x!=f[x]){
		int t=f[x];
		f[x]=find(f[x]);
		re[x]^=re[t];//更新根节点与父节点关系 
	}
	return f[x];
} 
void ufs(int a,int b){
	int x=find(a);
	int y=find(b);
	f[x]=y;
	re[x]=(re[a]+re[b]+1)%2;//根节点与根节点关系 
}
int main(){
	int n,m,a,b;
	char ch[10];
	scanf("%d",&t);
	while(t--){
		scanf("%d%d",&n,&m);
		for(int i=1;i<=n;i++){
			re[i]=0;
			f[i]=i;
		}
		for(int i=1;i<=m;i++){
			scanf("%s%d%d",ch,&a,&b);
			if(ch[0]=='A'){
				if(find(a)==find(b)){
					if(re[a]==re[b]){
						cout<<"In the same gang."<<endl;
					}else{
						cout<<"In different gangs."<<endl;
					}
				}/*else if(f[a]==a&&b==f[b]){//考虑得太片面了,有可能存在两个联通分支,一个只有一个节点,另外一个有2个以上,所以以上not sure cout<<"Not sure yet."<<endl; }*/else{
					cout<<"Not sure yet."<<endl;
				} 
			}else {
				ufs(a,b);
			}
		}
	}
}