luogu#P5092. [USACO04OPEN] Cube Stacking

[USACO04OPEN] Cube Stacking

Problem Description

John and Bessie are playing a cube game. There are nn cubes numbered 1n1\ldots n (1n300001 \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 PP commands (1P1000001 \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 PP. The next PP 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.

6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4
1
0
2

Hint

Some Constraints are shown in the Input Format.

1X,Yn1 \le X, Y \le n.

Translated by ChatGPT 5