A Coin Game
Time limit2sMemory limit512 MB
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:
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.