Grid Scramble

5

1 votes
Mathematics, Medium, approved, Mathematics, Mathamatics
Problem

Charlie has a grid G with N rows and M columns. The rows are numbered 0 through N1 from top to bottom. The columns are numbered 0 through M1 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],0i<N,0j<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:

  • Swap any two rows
  • Swap any two columns

Let S denote the set of distinct grids G that Charlie can generate from the input grid G.

You need to print the sum GSF(G)2
Since the result can be large, print it modulo 109+7

Input Format:

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 Format:

Output the desired sum modulo 109+7 in a single line.

Constraints

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:
2N,M

Subtask 1 (36 files):
N,M3

Subtask 2 (27 files):
N,M7

Subtask 3 (18 files):
N,M50

Subtask 4 (9 files):
N,M300

Subtask 5 (10 files):
N,M1500

Sample Input
2 3
2 5 1
6 3 4
Sample Output
24
Time Limit: 3
Memory Limit: 256
Source Limit:
Explanation

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

Editor Image

?