The classic Towers of Hanoi puzzle features three numbered pegs: , , and . disks of different diameters are initially stacked on peg , arranged so that the lower a disk, the larger its diameter. The goal is to move all the disks to peg , using peg as auxiliary.
You may move only the topmost disk of any stack in a single move, and never place a disk of larger diameter atop a smaller one.
At any time, the arrangement of disks is described by a sequence : element D_i specifies the peg on which disk is located. For example, after the third move (when disks are numbered by increasing diameter), the configuration is D = (3, 3, 1): the first and second disks are on peg , and the third disk is on peg .
Example. Suppose that disks are on peg . The table below (not shown) lists the disks' distribution during the moves (disks are numbered in order of increasing diameter).
Your task is: given an arbitrary sequence , determine how many optimal moves from the game's start are required to reach this position. If the position cannot occur during optimal play, output -1.
Reference. The optimal algorithm is described recursively by:
procedure Hanoi(N: \text{integer};~ From, To\_, Temp: \text{integer}); Begin if N > 0 then begin Hanoi(N-1, From, Temp, To\_); writeln(N, From, To\_); Hanoi(N-1, Temp, To\_, From) end End;
For example, to solve the puzzle for disks, call Hanoi(5, 1, 2, 3).
Note: During the game, the arrangement of disks across all pegs () never repeats, so the answer is always unique.
The first line contains the integer (1 \leq N \leq 31). The next lines contain the integers D_1, D_2, \ldots, D_N, one per line, where 1 \leq D_i \leq 3.
Output the number of moves required to reach this position, or -1 if impossible.
Example 1