Files
python/TangDou/AcWing_TiGao/T4/238.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

46 lines
1.4 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 30010;
int m;
int p[N], sz[N], d[N];
int find(int x) {
if (p[x] != x) {
int px = find(p[x]);
d[x] += d[p[x]]; // 距离
p[x] = px;
}
return p[x];
}
int main() {
scanf("%d", &m);
for (int i = 1; i < N; i++) p[i] = i, sz[i] = 1;
while (m--) {
char op[2]; // 读入一个操作符的办法:读入一个字符串,只用op[0]
scanf("%s", op);
int a, b;
scanf("%d %d", &a, &b);
if (op[0] == 'M') {
int pa = find(a), pb = find(b);
if (pa != pb) { // 如果a,b不在同一个集合中,需要合并集合
d[pa] = sz[pb]; // 需要在它家族人数未修改前,记录下pa前面的船的数量,否则,修改完就没机会了
sz[pb] += sz[pa]; // 维护pb家族人员数量
p[pa] = pb; // 将pa加入pb家族
}
} else {
int pa = find(a), pb = find(b);
if (pa != pb) // 不在一起
puts("-1");
else
// 注意:题目C操作问的是间隔多少条船,若a != b,
// 则间隔abs(d[a] - d[b]) - 1条船,若a == b,则间隔0条船
cout << max(0, abs(d[a] - d[b]) - 1) << endl;
}
}
return 0;
}