P5092 [USACO04OPEN] Cube Stacking
Description
John and Bessie are playing a cube game. There are $n$ cubes numbered $1\ldots n$ ($1 \leq n \leq 30000$) placed on the ground at the start, each forming a single-cube pile.
After the game starts, John will give Bessie $P$ commands ($1 \leq P \leq 100000$). There are two types of commands:
1. Move (`M`): Move the pile containing `X` onto the top of the pile containing `Y`.
2. Count (`C`): Count how many cubes are below cube `X` in the pile containing `X`.
Write a program to help Bessie complete the game.
Input Format
The first line contains $P$. The next $P$ lines each contain one command, in the form `M X Y` or `C X`.
The input guarantees that there will be no command that moves a pile onto itself.
Output Format
For each count command, output one line with one integer, which is the result.
Explanation/Hint
Some Constraints are shown in the Input Format.
$1 \le X, Y \le n$.
Translated by ChatGPT 5