Rotation Parity
Time limit5sMemory limit256 MB
Decide the parity of the number of 2x2 clockwise rotations needed to sort a permutation of an R x C grid into row-major order.
- Level
Hard8 of 10
- Topics
- Math, Combinatorics, Implementation, Sorting
- Solved
- No attempts yet
Problem
The archaeologist Diana Jones has found a secret passage to hidden treasure near Nowhere, Kansas. A stone gate blocks the passage, and an ancient unlocking mechanism is chiselled into the gate. Diana recognized the chiselled symbols at once.
- The mechanism is a table with rows and columns. Each cell holds one integer between and , and no value appears twice. At first glance the numbers look randomly placed.
- The mechanism has cogwheels that rearrange the cells. In one move Diana rotates a group of adjacent cells clockwise by degrees.
- The gate opens when the numbers are sorted in row-major order. The upper left cell must hold , the cell to its right , and so on until the lower right cell, which must hold .
The arrangement in the picture below is unlocked by two moves.

Diana does not need the moves themselves, only whether their number is even or odd. One arrangement admits many unlocking sequences, and all of them have the same length parity. Given the initial arrangement, write a program that decides whether the number of moves is even or odd.
Input
The first line contains the integers and ().
Each of the next lines contains integers (), the values chiselled into the cells of the initial arrangement. All values are different.
The given arrangement can always be unlocked.
Output
Print if the number of moves is even and if it is odd.
Hint
The arrangement in the picture is sorted by first rotating the group whose upper left corner sits in row 1 and column 1, then the group whose upper left corner sits in row 1 and column 2. That is two moves, so the answer is .