题干
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:
D [a] [b]
where [a] and [b] are the numbers of two criminals, and they belong to different gangs.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.
题解
这个题目有点绕
#include<cstdio>
#include<cstring>
const int MAX = 1000000;
//将有联系的人放到同一个集合里面,不管是不是同一团伙,只要有联系就放到同一集合
//然后用rela数组区分同一集合内是不是同一团伙
int father[MAX];//并查集数组
//int count;//集合的个数
int rela[MAX];//rela[i]表示i与其父亲结点的关系,0表示同一团伙,1表示不同团伙
void init_set(int n){
for(int i=1;i<=n;i++){father[i] = i;rela[i]=0;}
}
int find(int x){
int tmp = father[x];
if(x == father[x])
return x;
father[x] = find(father[x]);
//因为最上层也就是根节点的父亲一定是同一团伙的,也就是rela一定为0
//如果x与其未更新前的父亲属于同一团伙,则rela为0
//如果x与其未更新前的父亲属于不同团伙,则rela为1
//如果rela[x]!=rela[tmp]则说明x的父亲没有挂到别的集合
rela[x] = (rela[x] == rela[tmp]) ? 0 : 1;
return father[x];
}
void unin(int x,int y){
int fx = find(x);
int fy = find(y);
father[fx] = fy;
//
//如果rela[x]==0&&rela[y]==1则朋友的 敌人的敌人 就是我的朋友
//如果rela[x]==0&&rela[y]==0则朋友的 敌人的朋友 就是我的敌人
//如果rela[x]==1&&rela[y]==0则敌人的 敌人的朋友 就是我的朋友
//如果rela[x]==1&&rela[y]==1则敌人的 敌人的敌人 就是我的敌人
rela[fx] = (rela[x] == rela[y]) ? 1 : 0;
}
int main(){
int T,N,M;
scanf("%d",&T);
while(~scanf("%d%d",&N,&M)){
init_set(N);
char s[5];
int l,r;
for(int i=0;i<M;i++){
scanf("%s%d%d",s,&l,&r);
if(strcmp(s,"D")==0){
unin(l,r);
}else{
int x = find(l);
int y = find(r);
if(x!=y){
printf("Not sure yet.\n");
}else{
if(rela[l]==rela[r]){
printf("In the same gang.\n");
}else{
printf("In different gangs.\n");
}
}
}
}
}
return 0;
}