#P1196. [NOI2002] 银河英雄传说
[NOI2002] 银河英雄传说
Description
Yang Wen-li excels at troop deployment and cleverly uses various tactics to win many battles with fewer forces, which inevitably led to some pride. In this decisive battle, he divided the battlefield of the Barmilian starfield into columns, numbered in order. Then, he numbered his warships , placing warship in column , forming a "single-file long snake" formation to lure the enemy deeper. This is the initial formation. When the invading enemy arrives, Yang will repeatedly issue merge commands to concentrate most of the warships into a few columns for a dense attack. A merge command is M i j, meaning the entire warship queue containing warship , as a whole (head at the front and tail at the back), is appended to the tail of the warship queue containing warship . Clearly, a warship queue is composed of one or more warships that are in the same column. Executing a merge command will increase the size of a queue.
However, the cunning Reinhard has already taken the strategic initiative. During the battle, through a vast intelligence network, he can eavesdrop on Yang’s fleet maneuver commands at any time.
While Yang issues commands to maneuver the fleet, Reinhard will also issue query commands to promptly learn the current distribution of Yang’s warships: C i j. This command asks the computer whether Yang’s warships and are currently in the same column. If they are in the same column, it asks how many warships are placed between them.
As a seasoned senior programmer, you are required to write a program to process Yang’s commands and answer Reinhard’s queries.
The decisive battle has begun, and another page in the galaxy’s history has turned.
Input Format
The first line contains an integer (), indicating there are instructions in total.
Then follow lines, each containing one instruction. There are two formats:
-
M i j: and are two integers (), representing the warship IDs involved. This instruction is a fleet maneuver command issued by Yang that Reinhard has intercepted, and it is guaranteed that warships and are not in the same column. -
C i j: and are two integers (), representing the warship IDs involved. This instruction is a query issued by Reinhard.
It is guaranteed that in every instruction .
Output Format
Process each input instruction in order:
- If it is a fleet maneuver command issued by Yang, the fleet formation changes; your program should record the change but must not output anything.
- If it is a query issued by Reinhard, output one line containing a single integer: if warships and are in the same column, output the number of warships placed strictly between them; otherwise, output .
4
M 2 3
C 1 2
M 2 4
C 4 2
-1
1
Hint
Sample explanation
Warship position diagram: in the table, Arabic numerals denote warship IDs.

Translated by ChatGPT 5
京公网安备 11011102002149号