This page is still under construction.

Parts of this page are still being built. What you see may change.

A Coin Game

Time limit2sMemory limit512 MB

Summary
Given a starting row of 1 to n coins, find the minimum number of single-coin adjacent moves to sort them into increasing order, or report IMPOSSIBLE.
Level

Medium6 of 10

Topics
BFS, Simulation, Implementation, Brute force
Solved
No attempts yet

Problem

When she is bored, Jo Coder likes to play the following game with coins on a table. She takes a set of distinct coins and lines them up in a row. For example, suppose she has a penny (P, worth $0.01), a nickel (N, worth $0.05), and a dime (D, worth $0.10). She lines them up in an arbitrary order (for example, D N P) and then rearranges them so that they end up in strictly increasing order by value, that is P N D (i.e., $0.01, $0.05, $0.10). She follows these rules:

  • The initial line-up fixes every position where a coin may be placed. No new positions can be added later, and a position keeps existing even when it holds no coin.
  • The game is a sequence of moves. In each move Jo moves one coin from its current position to an adjacent position.
  • Coins may be stacked. In a move Jo always takes the top coin of one stack and drops it on top of another stack (or onto an empty position).
  • Within a stack, Jo never places a higher-value coin on top of a lower-value coin.

For simplicity, assign the coins consecutive integer values (e.g., the penny is 1, the nickel is 2, the dime is 3). With those values the example above can be solved in 20 moves. In the table below, XY means coin X sits on top of coin Y:

MovePosition 1Position 2Position 3
initial321
1312
2132
3132
4312
5312
6312
7132
8132
9123
10123
11231
12231
13213
14123
15123
16213
17213
18213
19123
20123

For some starting configurations it is impossible to reach the strictly increasing goal.

Input

The input contains several test cases. Each test case consists of two lines. The first line holds a positive integer n (n < 5), the number of coins; the coins are labeled 1, 2, 3, …, n. The second line lists the numbers 1 to n in an arbitrary order, giving the initial arrangement from the first position to the last.

A line containing a single 0 marks the end of the input.

Output

For each test case, print a single line: either the minimal number of moves in which Jo can reach the goal arrangement, or IMPOSSIBLE if the goal cannot be reached.

Examples3

  1. Example 1

    Input
    3
    3 2 1
    2
    2 1
    0
    
    Expected output
    20
    IMPOSSIBLE
    
  2. Example 2

    Input
    1
    1
    0
    
    Expected output
    0
    
  3. Example 3

    Input
    2
    1 2
    0
    
    Expected output
    0