Riddicks Cube#7476

Riddicks Cube

1 second
64 megabytes
Medium

It is well known, that the most sold toy in history is Rubik's Cube. In mere years million items were sold.

A famous Kazakhstani businessman decided to repeat that success, by creating a simpler version of this puzzle. Riddick's Cube, the ingenious invention of the businessman, is an n \times m rectangle consisting of 1 \times 1 cells, each of which is colored in some color. The rules of the puzzle are simple: in a single move it is allowed to cyclically move any row or column by one cell in any direction (rows are moved left or right, columns are moved up or down). For example, this is how -nd row is moved right and how -rd column is moved up:

prb7476.gif

A configuration of the puzzle is called final, if either each of the rows contains cells of the same color or each column contains cells of the same color.

The businessman is concerned about the solvability of his puzzle and so he wants to estimate its complexity before starting the sales. And he gives that task to you. To estimate the complexity we will simplify the rules: you can shift some columns (possibly none) and then some rows (possibly none).

You are given a configuration of one of the Riddick's Cubes. If a final configuration can be reached using the simplified rules, then the complexity of the configuration is equal to the minimal number of moves, leading to a final configuration. If a final configuration cannot be reached using the simplified rules, then the Cube is said to be mega complex and its complexity is equal to (probably, the puzzle can still be solved using the normal rules, but it's too complex).

Input

First line contains two integer numbers and ( ≤ , ≤ ). The following lines contain integer numbers each — the description of the puzzle. Each number describes a color in which a corresponding cell is colored. The color numbers are integer numbers in range from to . It is not guaranteed that the given configuration is solvable using even normal rules.

Output

Output one integer number - complexity of the given configuration of the puzzle.

Examples

Example 1

Loading
Loading

Example 2

Loading
Loading