并查集——Find The Catch The(两个帮派)

#include<iostream>
#include<cstdio>
using namespace std;
const int N = 100000;
int s[N*2+1];
int n,m,t;
void init_set(){
	for(int i = 1;i<=2*n;i++){
		s[i] = i;
	}
}
int find_set(int x){//代替递归的 
	int r = x;
	while(r!=s[r])r = s[r];//找到根节点 
	int i = x,j;
	while(i!=r){//往回找的时候,顺便把路上的左右set的值都变成根节点,深度就为1了 
		j = s[i];//保存了原本 i的祖先 
		s[i] = r; 
		i = j;	 
	}
	return r;
}
void union_set(int x,int y){
	s[find_set(y)] = find_set(x);
}
int main(){
	cin>>t;
	while(t--){
		cin>>n>>m;
		init_set();
		for(int i = 1;i<=m;i++){
			int x,y;
			char mode;
			getchar(); 
			scanf("%c%d%d",&mode,&x,&y);
			if(mode=='D'){
				union_set(x,y+n);
				union_set(x+n,y);
			}
			else{
				   if((find_set(x)==find_set(y))||(find_set(x+n)==find_set(y+n))) cout<<"In the same gang."<<endl;
				   else if((find_set(x)==find_set(y+n))||(find_set(x+n)==find_set(y))) cout<<"In different gangs."<<endl;
				   else cout<<"Not sure yet."<<endl;
			}
		}	
	}
	return 0;
}
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页