#P5092. Cube Tower Game

    ID: 18330 Type: Default 1000ms 256MiB

Cube Tower Game

Cube Tower Game

John and Betsy are playing a cube tower game. Initially, there are n blocks numbered from 1 to n (where \(1 \leq n \leq 30000\)) and each block is placed as a separate tower (or column). The game consists of P commands (where \(1 \leq P \leq 100000\)). There are two types of commands:

  • Move (M): Move the entire tower containing block \(X\) on top of the tower containing block \(Y\).
  • Count (C): For block \(X\), count the number of blocks below it in its current tower.

Write a program to help Betsy complete the game.

inputFormat

The first line contains two integers \(n\) and \(P\), representing the number of blocks and the number of commands respectively.

Each of the following \(P\) lines contains a command in one of the following formats:

  • C X : Query the number of blocks below block \(X\).
  • M X Y : Move the entire tower containing block \(X\) onto the top of the tower containing block \(Y\).

It is guaranteed that all commands are valid.

outputFormat

For each query command (C), output one integer on a separate line representing the number of blocks below the queried block.

sample

4 7
C 1
M 1 2
C 1
M 3 4
C 3
M 1 4
C 1
0

1 1 3

</p>