Charlie has a grid G with N rows and M columns. The rows are numbered 0 through N−1 from top to bottom. The columns are numbered 0 through M−1 from left to right.
Each cell of the grid G contains a positive integer in the range [1,N×M]. Each of these numbers occurs in the grid exactly once.
In Charlie's eyes, the most beautiful of all grids is the sorted grid GS : A grid of size N×M whose list of elements in row major order is the ordered sequence [1,2,3,...,N×M]. For example with N=2 and M=3, GS=[123456]
Denote F(G) = Number of pairs (i,j) such that G[i][j]=GS[i][j],0≤i<N,0≤j<M
For example:
F([123456])=6,
F([321546])=2
Charlie can also modify the grid by applying the following two operations any number of times:
Let S denote the set of distinct grids G that Charlie can generate from the input grid G.
You need to print the sum ∑G′∈SF(G′)2
Since the result can be large, print it modulo 109+7
The first line will contain two integers N,M.
The next N lines will contain M integers each. The ith line describes the numbers in the ith row of G.
The input grid numbers are guaranteed to be a permutation of [1,2,3,..,N×M].
Output the desired sum modulo 109+7 in a single line.
There are 100 files. Your solution will get a score equal to the number of files you pass. Some files may have different bounds, as detailed below.
For all subtasks:
2≤N,M
Subtask 1 (36 files):
N,M≤3
Subtask 2 (27 files):
N,M≤7
Subtask 3 (18 files):
N,M≤50
Subtask 4 (9 files):
N,M≤300
Subtask 5 (10 files):
N,M≤1500
There are 12 configurations we can reach
F([251634])=0,
F([215643])=0,
F([521364])=1,
F([512346])=1,
F([125463])=3, F([152436])=3, F([634251])=1, F([643215])=1,
F([364521])=0, F([346512])=0, F([463125])=1, F([436152])=1
The sum of F(G)2 is equal to 12+12+32+32+12+12+12+12=24