带权并查集
rank数组表示的是属于哪个集合。树根的rank均为0,
#include<cstdio>
#include<cstring>
using namespace std;
int n,m;
int f[500100],rank[500100];
void init(){
int i,j;
for(i=1;i<=n;i++){
f[i]=i;
rank[i]=0;
}
}
int find(int a){
int temp=f[a];
if(f[a]!=a){
f[a]=find(f[a]);
rank[a]=(rank[a]+rank[temp])%2;
}
return f[a];
}
void merge(int a,int b){
int x=find(a);
int y=find(b);
f[y]=x;
rank[y]=(rank[a]+rank[b]+1)%2;
}
int main(){
int t,T,i,j,a,b;
char s[10];
scanf("%d",&T);
for(t=1;t<=T;t++){
scanf("%d %d",&n,&m);
init();
for(i=1;i<=m;i++){
scanf("%s %d %d",&s,&a,&b);
if(s[0]=='D'){
merge(a,b);
}
else if(s[0]=='A'){
int x=find(a);
int y=find(b);
if(x==y && rank[a]==rank[b])
printf("In the same gang.\n");
else if(x==y && rank[a]!=rank[b])
printf("In different gangs.\n");
else if(x!=y)
printf("Not sure yet.\n");
}
}
}
}