Description
约翰和贝茜在玩一个方块游戏.编号为 1 到
游戏开始后,约翰会给贝茜发出P(1≤P≤100000)个指令.指令有两种:
- 移动(M): 将包含 X 的立方柱移动到包含
Y 的立方柱上. - 统计(C): 统计名含 X 的立方柱中,在
X 下方的方块数目
写个程序帮贝茜完成游戏.
Input
第 1 行输入
输入保证不会有将立方柱放在自己头上的指令.
Output
每一行,对于每个统计指令,输出其结果.
Sample Input
6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4
Sample Output
1
0
2
Solution
带权并查集。记录三个信息,
#include<bits/stdc++.h>
using namespace std;
#define N 100001
inline int read() {
int x = 0, flag = 1; char ch = getchar(); while (!isdigit(ch)) { if (!(ch ^ '-')) flag = -1; ch = getchar(); }
while (isdigit(ch)) x = (x << 1) + (x << 3) + ch - '0', ch = getchar(); return x * flag;
}
inline void write(int x) {
if (!x) { putchar('0'); return; } if (x < 0) putchar('-'), x = -x;
char buf[30] = ""; int top = 0; while (x) buf[++top] = x % 10 + '0', x /= 10; while (top) putchar(buf[top--]);
}
int fa[N], dn[N], dis[N];
int find(int x) {
if (fa[x] ^ x) { int y = fa[x]; fa[x] = find(y), dis[x] += dis[y], dn[x] = dn[y]; } return fa[x];
}
int main() {
int q = read(); rep(i, 1, q) fa[i] = dn[i] = i, dis[i] = 0;
while (q--) {
char s[5]; scanf("%s", s);
if (!(s[0] ^ 'M')) {
int x = read(), y = read(), fx = find(x), fy = find(y);
fa[fy] = fx, dis[fy] = dis[dn[fx]] + 1, dn[fx] = dn[fy];
find(dn[x]), find(dn[y]);
}
else { int x = read(); find(x); write(dis[dn[x]] - dis[x]), puts(""); }
}
return 0;
}