题意:有两个帮派,总共有n个人,有m次查询 D x y代表x和y不是一个帮派,A x y代表查询x和y是否是一个帮派。
题解:并查集开两倍数组,为D时 连接 x+n和y ,x和y+n 。当查询时当x和y或x+n和y+n的根节点相同,则为一个帮派,
当x和y+n或x+n和y的根节点相同则为不同帮派,其他未知。
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstring>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define ll long long
#define Max 100000
using namespace std;
const int inf = 0x3f3f3f3f;
int d;
int use[1110];
struct node{
int x,y;
int pre;
int root;
}a[200010];
int init(int n){
for(int i = 1 ; i <= n ; i++){
a[i].pre = i;
a[i].root = 1;
}
}
int find_pre(int x){
if(a[x].pre==x){
return x;
}
return a[x].pre = find_pre(a[x].pre);
}
bool is_s(int x,int y){
return find_pre(x)==find_pre(y);
}
void unite(node x,node y){
int rootx,rooty;
rootx = find_pre(x.pre);
rooty = find_pre(y.pre);
if(rootx == rooty){
return;
}
if(a[rootx].root > a[rooty].root){
a[rooty].pre = rootx;
}else{
if(a[rootx].root == a[rooty].root){
a[rooty].root++;
}
a[rootx].pre = rooty;
}
}
int main(){
int T,x,y,n,m;
cin>>T;
while(T--){
scanf("%d %d",&n,&m);
init(n*2);
getchar();
char ch;
for(int i = 0 ; i < m ; i++){
scanf("%c %d %d",&ch,&x,&y);
getchar();
if(ch=='D'){
unite(a[x],a[y+n]);
unite(a[x+n],a[y]);
}else{
if(is_s(y+n,x+n)||is_s(x,y)){
cout<<"In the same gang."<<endl;
}else if(is_s(y+n,x)||is_s(x+n,y)){
cout<<"In different gangs."<<endl;
}else{
cout<<"Not sure yet."<<endl;
}
}
}
}
}