添加链接描述
#include<bits/stdc++.h>
using namespace std;
const int N=5e5+9;
int fa[N],sum[N],front[N];
int find(int x){
if(x==fa[x])return fa[x];
int fn=find(fa[x]);
front[x]+=front[fa[x]];
return fa[x]=fn;
}
int main(){
for(int i=1;i<=5e5;i++){
fa[i]=i;
sum[i]=1;
front[i]=0;
}
int T;
cin>>T;
while(T--){
char ch;
cin>>ch;
int a,b;
cin>>a>>b;
if(ch=='M'){
a=find(a),b=find(b);
if(a!=b){
front[a]+=sum[b];
sum[b]+=sum[a];
sum[a]=0;
fa[a]=b;
}
}
else {
if(find(a)==find(b)){
cout<<abs(front[a]-front[b])-1<<"\n";
}
else cout<<"-1\n";
}
}
return 0;
}
文章评论