AC on #1,其余WA。
code:
#include <bits/stdc++.h>
#define N 30005
using namespace std;
int T, x, y, fa[N], dis[N];
char op;
void init()
{
for (int i = 0; i < N; i++)
fa[i] = i, dis[i] = 0;
}
int find(int x)
{
if (fa[x] == x)
return x;
int tmp = fa[x];
fa[x] = find(fa[x]);
dis[x] += dis[tmp];
return fa[x];
}
void merge(int x, int y)
{
int fx = find(x), fy = find(y);
if (fx != fy)
{
fa[fx] = fy;
dis[fx] = 1;
}
}
int main()
{
init();
cin >> T;
while (T--)
{
cin >> op >> x >> y;
if (op == 'M'){
merge(x, y);
// for (int i = 1; i <= 4; i++)
// cout << fa[i] << ' ';
// cout << endl;
}
else if (op == 'C')
{
int fx = find(x), fy = find(y);
if (fx != fy)
cout << -1 << endl;
else
{
if (dis[x] < dis[y])
swap(x, y);
cout << dis[x] - dis[y] - 1 << endl;
}
}
}
return 0;
}