A Strange Tower of Hanoi

Time limit2sMemory limit512 MB

Summary
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 NN 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 NN 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 NN (1≤N≤1231 \le N \le 123).

The second line contains the radii a1,a2,…,aNa_1, a_2, \dots, a_N (1≤ai≤N1 \le a_i \le N) 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.

  1. Let MM be the largest radius among the disks still on rod 1 and rod 2.
  2. For i=1,2i = 1, 2, let did_i be the number of disks lying above the highest disk of radius MM on rod ii. If rod ii holds no disk of radius MM, then di=∞d_i = \infty.
  3. If d1≤d2d_1 \le d_2, set X=1X = 1 and Y=2Y = 2. Otherwise set X=2X = 2 and Y=1Y = 1.
  4. If the top disk of rod XX has radius MM, move it to rod 3. Otherwise move the top disk of rod XX to rod YY.

On the first line print the number of moves KK that the procedure makes. On each of the next KK lines print one move as A B (1≤A,B≤31 \le A, B \le 3), meaning that the top disk of rod AA moves to the top of rod BB. The procedure always finishes within N(N+1)2≤7626\frac{N(N+1)}{2} \le 7626 moves, so K≤12345K \le 12345 always holds.

Hint

The picture below shows how the sample is solved.

Examples1

  1. Example 1

    Input
    3
    2 3 1
    
    Expected output
    4
    1 2
    1 3
    1 3
    2 3