A Strange Tower of Hanoi
Time limit2sMemory limit512 MB
Simulate a fixed rule-based procedure that rearranges disks of arbitrary radii on three rods and outputs the resulting move sequence.
- Level
Medium4 of 10
- Topics
- Simulation, Implementation
- Solved
- No attempts yet
Problem
There are three rods, and rod 1 holds a stack of disks. You move one disk at a time. A single move takes the top disk of one rod and puts it on top of another rod.
Seungmin changed the classic Tower of Hanoi puzzle in two places. First, he deleted the rule that a stacked disk must always be smaller than the disk below it, intermediate states included, so while you are moving disks you may put a large disk on a small one. Second, the disks on rod 1 start in an arbitrary order that has nothing to do with their radii.
The goal is to move all disks to rod 3. In the final state the radii on rod 3 must not increase from the bottom to the top, so no disk ends up resting on a disk with a strictly smaller radius.
Seungmin gave the puzzle to Jinsu and promised him pizza if the number of moves is at most 12345. Help Jinsu get the pizza.
Input
The first line contains the number of disks ().
The second line contains the radii () of the disks on rod 1, separated by spaces. They are listed starting from the radius of the bottom disk. Several disks may have the same radius.
Output
The puzzle has many valid answers, so print the move sequence produced by the procedure below. While at least one disk remains on rod 1 or rod 2, repeat these four steps.
- Let be the largest radius among the disks still on rod 1 and rod 2.
- For , let be the number of disks lying above the highest disk of radius on rod . If rod holds no disk of radius , then .
- If , set and . Otherwise set and .
- If the top disk of rod has radius , move it to rod 3. Otherwise move the top disk of rod to rod .
On the first line print the number of moves that the procedure makes. On each of the next lines print one move as A B (), meaning that the top disk of rod moves to the top of rod . The procedure always finishes within moves, so always holds.
Hint
The picture below shows how the sample is solved.
