CF BUDDY
← Problems·

1294E · Obtain a Permutation

1900 · greedy, implementation, math

Problem: You are given a rectangular matrix of size n×mn \times m consisting of integers from 11 to 21052 \cdot 10^5.

In one move, you can:

  • choose any element of the matrix and change its value to any integer between 11 and nmn \cdot m, inclusive;
  • take any column and shift it one cell up cyclically (see the example of such cyclic shift below).

A cyclic shift is an operation such that you choose some jj (1jm1 \le j \le m) and set a1,j:=a2,j,a2,j:=a3,j,,an,j:=a1,ja_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \dots, a_{n, j} := a_{1, j} simultaneously.

Example of cyclic shift of the first column

You want to perform the minimum number of moves to make this matrix look like this:

In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,,a1,m=m,a2,1=m+1,a2,2=m+2,,an,m=nma_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m (i.e. ai,j=(i1)m+ja_{i, j} = (i - 1) \cdot m + j) with the minimum number of moves performed.

Input Format: The first line of the input contains two integers nn and mm (1n,m2105,nm21051 \le n, m \le 2 \cdot 10^5, n \cdot m \le 2 \cdot 10^5) — the size of the matrix.

The next nn lines contain mm integers each. The number at the line ii and position jj is ai,ja_{i, j} (1ai,j21051 \le a_{i, j} \le 2 \cdot 10^5).

Output Format: Print one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,,a1,m=m,a2,1=m+1,a2,2=m+2,,an,m=nma_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m (ai,j=(i1)m+ja_{i, j} = (i - 1)m + j).

Note: In the first example, you can set a1,1:=7,a1,2:=8a_{1, 1} := 7, a_{1, 2} := 8 and a1,3:=9a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.

In the second example, the matrix is already good so the answer is 00.

In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.

Sample Cases

Case 1

Input

3 3
3 2 1
1 2 3
4 5 6

Output

6

Case 2

Input

4 3
1 2 3
4 5 6
7 8 9
10 11 12

Output

0

Case 3

Input

3 4
1 6 3 4
5 10 7 8
9 2 11 12

Output

2

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback