P1196 [NOI2002] 银河英雄传说https://www.luogu.com.cn/problem/P1196
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <cmath>
#include <map>
#include <cstdlib>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MN = 65005;
const int MAXN = 1000010;
const int INF = 0x3f3f3f3f;
#define IOS ios::sync_with_stdio(false)
#define lowbit(x) ((x)&(-x))
int pre[MAXN];
int d[MAXN];
int siz[MAXN];
int find(int x) {
if (x == pre[x]) {
return x;
}
int root = find(pre[x]);
d[x] += d[pre[x]];
pre[x] = root;
return root;
}
void unite(int x, int y) {
x = find(x);
y = find(y);
pre[x] = y;
d[x] = siz[y];
siz[y] += siz[x];
}
bool inline same(int x, int y) {
return find(x) == find(y);
}
int main() {
int t;
scanf("%d", &t);
for (int i = 1; i <= 30000; i++) {
siz[i] = 1;
pre[i] = i;
}
char ch;
int x, y;
while (t--) {
scanf(" %c %d %d", &ch, &x, &y);
if (ch == 'M') {
unite(x, y);
} else {
if (same(x, y)) {
printf("%d\n", abs(d[x] - d[y]) - 1);
} else {
printf("-1\n");
}
}
}
return 0;
}