天天看点

Find them, Catch them

        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.

题意:A 1 2是询问1和2这两个人是不是一个帮派,D 1 2是这两个人不在一个帮派,每一次A就输出一次 

题解:敌人的敌人是朋友:判断时,只要查找他们的祖先是不是同一人呢?如果是,说明两个人在一个帮派;

若不是,还要进行判断,如果A和 B的敌人 是一个祖先,可以判断A,B不是同一个帮派。否则不能确定关系。

set是同一个来确定这两个元素之间的关系。set[a]中存放的是x的根结点,flag中存放的是father[a]与a的关系,表示的是子节点和其父节点的关系,是一个帮派就是1,不是就是0


       
#include<iostream>
#include<algorithm>
#define N 100005
using namespace std;
int set[N];
int flag[N];
void Init_set(int n){
	for(int i=0;i<n;i++){
		set[i]=i;
		flag[i]=1;
	}
}
int find(int x){
	int temp=set[x];
	if(x==set[x])
		return x;
	set[x]=find(set[x]);
           
//如果子节点和父节点是同类就存0
	flag[x]=(flag[x]==flag[temp])?1:0;
	return set[x];
}
void merge(int a,int b){
	int ax=find(a);
	int by=find(b);
	if(ax!=by){
		set[ax]=by;
		//括号中是flag[x],不是flag[ax] 
		flag[ax]=(flag[a]==flag[b])?0:1;
	}
}
int main(){
	int t;
	cin>>t;
	while(t--){
		int n;
		int m;
		cin>>n>>m;
		Init_set(n);
		while(m--){
			getchar();
			int x;
			int y;
			char c;
			scanf("%c%d%d",&c,&x,&y);
			if(c=='D')
				merge(x,y);
			else{
				int ax=find(x);
				int by=find(y);
				if(ax!=by)
					cout<<"Not sure yet."<<endl;
				else if(flag[x]==flag[y])
					cout<<"In the same gang."<<endl;
				else
					cout<<"In different gangs."<<endl;
			}
		}
	}
	return 0; 
}