#P6687. 180° Rotation on a 2×n Grid
180° Rotation on a 2×n Grid
180° Rotation on a 2×n Grid
We are given a 2×n grid that is filled with all the integers from 1 to 2×n without any repetition. You are allowed to perform the following operation any number of times:
- Select any contiguous 2×2 subgrid (i.e. two adjacent columns) and rotate it 180°.
The operation on a 2×2 block works as follows. Suppose the selected block is \[ \begin{bmatrix} a & b\\ c & d \end{bmatrix} \] then after a 180° rotation it becomes \[ \begin{bmatrix} d & c\\ b & a \end{bmatrix} \]
You are given the initial state and a target state of the grid. Determine if it is possible to transform the initial state into the target state using the allowed operations. If it is possible, compute and output the minimum number of operations required; otherwise, output -1.
Hint: Each operation performs two independent swaps, so the overall parity of the permutation of numbers in the grid (when read row‐wise) is invariant. The transformation is possible if and only if the permutation from the initial state to the target state is even.
inputFormat
The first line contains a single integer n
(the number of columns).
The next two lines each contain n
integers describing the initial state. The first of these lines gives the top row and the second gives the bottom row.
The following two lines each contain n
integers describing the target state (first top row, then bottom row).
outputFormat
If the target state can be reached, output the minimum number of operations required. Otherwise, output -1.
sample
2
1 2
3 4
1 2
3 4
0
</p>