Problem C
Lista
Mirko received a birthday present from his aunt in the US –
a brand-new doubly-linked list (an example of which is shown in
the figure below). The list contains
-
Move node
in front of node . -
Move node
after node .
![\includegraphics[width=0.75\textwidth ]{lista}](/problems/lista/file/statement/en/img-0001.png)
Mirko played with his new toy for hours, writing down each
move on a piece of paper so that he can reconstruct the list’s
initial state (nodes
When he decided to reconstruct the list, Mirko was
astonished to find that there is no easy way to invert the
moves and restore the list’s initial state. Mirko cannot know
where node
Seeing how Mirko is still recovering from the shock, write a program that finds a shortest sequence of moves that restores the list to its initial state from Mirko’s logs.
Input
The first line of input contains two integers
Each of the next
Output
Output the minimum number of moves (call this number
Note: The sequence need not be unique.
Sample Input 1 | Sample Output 1 |
---|---|
2 1 A 2 1 |
1 A 1 2 |
Sample Input 2 | Sample Output 2 |
---|---|
4 3 B 1 2 A 4 3 B 1 4 |
2 A 1 2 B 4 3 |
Sample Input 3 | Sample Output 3 |
---|---|
6 5 A 1 4 B 2 5 B 4 2 B 6 3 A 3 5 |
3 A 4 5 B 6 5 A 2 3 |