Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
Register

## 简单的并查集实现方法。

Posted by 961592690 at 2019-02-25 17:30:31 on Problem 1703
```这个题不可以使用Cin

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
#define MAX_N 100005
int T;
int par[MAX_N*2]={0};
int rank[MAX_N*2];
void init(int x){
for(int i=1;i<=x;i++){
par[i]=i;
rank[i]=0;
}
}
int find(int x){
if(par[x]==x)
return x;
else
return par[x]=find(par[x]);
}
void unite(int x,int y){
x = find(x);
y = find(y);
if(x==y)
return;
if(rank[x]<rank[y])
par[x]=y;
else{
par[y]=x;
if(rank[x]==rank[y])
rank[x]++;
}
}
bool same(int x,int y){
return find(x)==find(y);
}
int main(){
scanf("%d",&T);
while(T--){
int M,N;
scanf("%d%d",&N,&M);
getchar();
memset(par,0,sizeof(par));
init(2*N);
for(int i=0;i<M;i++){
char cmd;
int c1,c2;
//cin>>cmd>>c1>>c2;
scanf("%c %d %d",&cmd,&c1,&c2);
getchar();
if(cmd=='D'){
unite(c1,c2+N);
unite(c1+N,c2);
}
else{
if(N==2)
printf("In different gangs.\n");
else if(same(c1,c2)){
printf("In the same gang.\n");
}
else if (same(c1,c2+N)||same(c1+N,c2))printf("In different gangs.\n");
else
puts("Not sure yet.");
}
}
}
}```

Followed by: