天天看點

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; 
}