import java.io.*; import java.util.*; /** * CCC '12 S4 - A Coin Game * Question type: Graph Theory * 50/50 on DMOJ * Question URL: https://dmoj.ca/problem/ccc12s4 * @author Tommy Pang */ public class j5 { static Scanner input = new Scanner(System.in); static int n; static Map vis; public static void main(String[] args) throws IOException { n = readInt(); do { vis = new HashMap<>(); List [] table = new List[n]; for (int i = 0; i < n; i++) { table[i] = new ArrayList<>(); table[i].add(readInt()); } int ans = BFS(table); System.out.println(ans==-1 ? "IMPOSSIBLE" : ans); n = readInt(); } while (n!=0); } public static int BFS(List [] list) { Queue []> queue = new LinkedList<>(); Queue dis = new LinkedList<>(); queue.add(list); // Queue with states dis.add(0); // Parallel queue: steps (distance of each state) while (!queue.isEmpty()) { // Get next state from queue List [] cur = queue.poll(); int d = dis.poll(); // DEBUG print(cur, d); // Is cur a finished state ? if (finished(cur)) return d; for (int i = 0; i < n-1; i++) { if (cur[i].size()==0) continue; List [] nxt = clone(cur); if (nxt[i].get(0)<(nxt[i+1].size()==0?Integer.MAX_VALUE:nxt[i+1].get(0))) { nxt[i+1].add(0, nxt[i].remove(0)); if (!visited(nxt)) { queue.add(nxt); dis.add(d+1); } } } for (int i = n-1; i > 0; i--) { if (cur[i].size()==0) continue; List [] nxt = clone(cur); if (nxt[i].get(0)<(nxt[i-1].size()==0?Integer.MAX_VALUE:nxt[i-1].get(0))) // ^^^^^^^^^^^^^^^^^^ position is OPEN { nxt[i-1].add(0, nxt[i].remove(0)); // Move top coin i->i-1 if (!visited(nxt)) { queue.add(nxt); dis.add(d+1); // Increase distance } } } } return -1; } public static boolean visited(List [] table) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { List col = table[i]; for (int nxt : col) { sb.append(nxt); } if (i!=n-1) sb.append("-"); } if (!vis.containsKey(sb.toString())) { vis.put(sb.toString(), sb.toString()); return false; } else return true; } public static boolean finished(List [] table) { for (int i = 0; i < n; i++) { if (table[i].size()!=1) return false; // More than 1 coin in a spot else if (table[i].get(0)!=i+1) return false; // Coin not in its correct position } return true; } // Clone a state (table entry) public static List [] clone(List [] table) { List [] ret = new List[table.length]; for (int i = 0; i < table.length; i++) { ret[i] = new ArrayList<>(table[i]); } return ret; } public static void print(List [] table, int d) { List x; for (int i = 0; i < table.length; i++) { x = table[i]; System.out.print(x + " "); } System.out.println(": " + d); } static int readInt() throws IOException { return input.nextInt(); } }