银河英雄传说
解:对M操作,用并查集维护即可。对于C操作,在合并结点的时候还需要维护s和d两个数组,s表示当前集合的大小,保存在根结点上,d表示当前元素到根结点的距离,保存在各个元素上。在合并结点的同时更新s与d数组,运用前缀和的思想,即可O(1)回答各个询问。
#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for(int i = a;i<n;i++)
#define per(i,a,n) for(int i = n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define eb emplace_back
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define yes cout<<"YES"<<'\n';
#define no cout<<"NO"<<'\n';
#define endl '\n';
typedef vector<int> VI;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef double db;
mt19937 mrand(random_device{}());
const ll MOD=1000000007;
int rnd(int x) {return mrand() % x;}
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;};
ll lcm(int a,int b){return a*b/gcd(a,b);};const int N=30010;
int n;
int p[N],s[N],d[N];int findd(int x){if(p[x]!=x){int root=findd(p[x]);d[x]+=d[p[x]];p[x]=root;}return p[x];
}int main(){ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);cin>>n;rep(i,0,N) p[i]=i,s[i]=1;rep(i,0,n){char op;int a,b;cin>>op>>a>>b;if(op=='M'){int pa=findd(a),pb=findd(b);if(pa!=pb){d[pa]=s[pb];s[pb]+=s[pa];p[pa]=pb;}}else{int pa=findd(a),pb=findd(b);if(pa!=pb){cout<<-1<<endl;}else cout<<max(0,abs(d[a]-d[b])-1)<<endl;}}return 0;
}