```cpp
#include<bits/stdc++.h>
using namespace std;
const int maxN=30001;
struct zj
{
int before,cnt,head;
}a[maxN];
int find(int i)
{
int f;
if(i==a[i].head) return i;
else
{
f=find(a[i].head);
a[i].before+=a[a[i].head].before;
a[i].head=f;
return f;
}
}
void modify(int i,int j)
{
int hi=find(i);
int hj=find(j);
a[hi].head=hj;
a[hi].before+=a[hj].cnt;
a[hj].cnt+=a[hi].cnt;
}
int query(int i,int j){
if(find(i)!=find(j)){
return -1;
}else{
return abs(a[i].before-a[j].before)-1;
}
}
int main()
{
int T,x,y,i;
char c;
cin>>T;
for(i=1;i<=30000;i++)
{
a[i].before=0;
a[i].cnt=1;
a[i].head=i;
}
for(i=1;i<=T;i++)
{
cin>>c>>x>>y;
if(c=='M') modify(x,y);
else cout<<query(x,y)<<endl;
}
return 0;
}
```
by shenrui @ 2018-12-16 15:50:22