Obtain a Permutation(思维)
You are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2?1052?105.
In one move, you can:
choose any element of the matrix and change its value to any integer between 11 and n?mn?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 (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,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=n?ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n?m (i.e. ai,j=(i?1)?m+jai,j=(i?1)?m+j) with the minimum number of moves performed.
Input
The first line of the input contains two integers nn and mm (1≤n,m≤2?105,n?m≤2?1051≤n,m≤2?105,n?m≤2?105) — the size of the matrix.
The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2?1051≤ai,j≤2?105).
Output
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=n?ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n?m (ai,j=(i?1)m+jai,j=(i?1)m+j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,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.
又是一個看著挺簡單的題目做了很久。
一開始就是類似于暴力做的,結果錯了很多次。。
一開始思路的一個誤區,我認為執行操作2的一定是一段連續的數字,就像1 4 7這樣的,但是這怎么可能呢?有可能兩個數字都要移動那么多的位置,但是他們之間的數字不是這樣的,這就要貪心取最優了。
這道題目,每一列是獨立的,所以我們應該每一列單獨去考慮。對于每一列中的,如果可以移動相同的次數,我們應該歸并到一起來計算,這樣就可以統計出移動次數0~n-1之間各有多少個數字。每一列這樣貪心取最優,就可以了。
代碼如下:
努力加油a啊,(o)/~
總結
以上是生活随笔為你收集整理的Obtain a Permutation(思维)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Aroma's Search(暴力)
- 下一篇: As Simple as One and