This page is still under construction.

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

Crazy Bits

Time limit1sMemory limit128 MB

Summary
Given initial and target 12-bit register values, find the minimum number of adjacent bit swaps (within and between registers) to transform one configuration into the other, or report impossibility.
Level

Hard8 of 10

Topics
BFS, Simulation, Graph, Bit manipulation
Solved
No attempts yet

Problem

The Olandicans have invented a strange computer. It has only 12-bit registers to store numbers, and the only command it accepts is SWAP. The SWAP function is called with three arguments ii, jj, and dd. A call swap(i, j, d) swaps the jjth bit of the iith register with its neighboring bit in direction dd (0: up, 1: right, 2: down, 3: left).

  • Right (1) and left (3) refer to a neighboring bit inside the same register (the (j+1)(j+1)th and (j−1)(j-1)th bit, respectively).
  • Up (0) and down (2) refer to the same bit position in a neighboring register (the (i−1)(i-1)th and (i+1)(i+1)th register, respectively).

For example, swap(2, 3, 1) swaps the 3rd and the 4th bits of the 2nd register, and swap(6, 4, 2) swaps the 4th bits of the 6th and the 7th registers.

The Olandicans know the initial values of the registers and want to change them into some other values. Find the minimum number of SWAP calls needed to turn every register into its desired value.

Input

The input consists of multiple test cases. The first line of each test case contains nn (1≤n≤161 \le n \le 16), the number of registers. The next line contains nn integers, where the iith number is the initial value of the iith register. The next line contains nn integers, where the iith number is the desired value of the iith register. Each register value is an integer between 00 and 40954095 inclusive (it fits in 12 bits). The input is terminated by a line containing a single zero.

Output

For each test case, print on a single line the minimum number of swaps needed. If it is impossible, print Impossible.

Examples3

  1. Example 1

    Input
    2
    2 3
    6 2
    3
    1 1 1
    2 3 4
    4
    5 2 6 0
    3 2 2 4
    0
    
    Expected output
    3
    Impossible
    2
    
  2. Example 2

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

    Input
    2
    1 0
    0 1
    0
    
    Expected output
    1