并查集
每个联通图内的元素之间都有相对关系rank,关系rank差1说明元素在不同的集团,rank相同说明在同一个集团。
询问a,b结点的关系的时候,当a,b不在一个联通图是关系未确定
a,b在一个联通图则比较rank
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <math.h>
using namespace std;
const int MAXN = 1000005;
int pre[MAXN];
int ranks[MAXN];
int find_DS(int r)
{
if(r == pre[r])return r;
int fa = pre[r];
pre[r] = find_DS(pre[r]);
ranks[r] = (ranks[r]+ranks[fa])%2;
return pre[r];
}
bool merge_DS(int a,int b)
{
int fx = find_DS(a),fy = find_DS(b);
if(fx == fy)return 0;
pre[fx] = fy;
ranks[fx] = (-ranks[a]+ranks[b]+1)%2;
return 1;
}
int main()
{
int T,N,M,a,b;
char s[2];
cin >> T;
while(T--){
cin >> N >> M;
for(int i = 1;i<=N;i++){
pre[i] = i;
ranks[i] = 0;
}
for(int i = 0;i<M;i++){
scanf("%s%d%d",s,&a,&b);
if(s[0] == 'D'){
merge_DS(a,b);
}
else{
int fa = find_DS(a),fb = find_DS(b);
if(fa != fb)printf("Not sure yet.\n");
else if(ranks[a] == ranks[b])printf("In the same gang.\n");
else printf("In different gangs.\n");
}
}
}
return 0;
}