显示代码纯文本
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=30010;
int n,father[maxn]={0},before[maxn]={0};
int Count[maxn]={1};bool panduan(int,int);
void hebing(int,int);
int Findroot(int);
int main()
{
freopen("galaxy.in","r",stdin);
freopen("galaxy.out","w",stdout);
int n;
cin>>n;
for(int i=1;i<=maxn;i++)
{
Count[i]=1;
father[i]=i;
}
for(int i=1;i<=n;i++)
{
char ch;int x,y;
cin>>ch>>x>>y;
if(ch=='M')
{
if(panduan(x,y)) continue;
else
{
//cout<<"+++++++++++======+++++++++++"<<endl;
hebing(x,y);
continue;
}
}
if(ch=='C')
{
if(panduan(x,y))
{
cout<<abs(before[x]-before[y])-1<<endl;
continue;
}
else
{
cout<<-1<<endl;
continue;
}
}
}
}
void hebing(int a,int b)
{
a=Findroot(a);
b=Findroot(b);
father[a]=b;
before[a]=Count[b];
Count[b]=Count[a]+Count[b];
}
int Findroot( int x)
{
if(father[x]!=x)
{
int re=Findroot(father[x]);
before[x]+=before[father[x]];
father[x]=re;
}
return father[x];
}
bool panduan(int x,int y)
{
return Findroot(x)==Findroot(y);
}