
You can’t decrease a number below 0.
You are given ‘K’ = 5, and matrix
‘mat’ = [[1, 2, 3],
[4, 0, 5],
[2 , 7, 4]]
You can do 3 operations on element 7 and 2 operations on element 5. Then the sum of all submatrices will be 246.
The first line of input contains a single integer ‘T’, denoting the number of test cases.
The first line of each test case contains three space-separated integers ‘N’, ‘M’, and ‘K’, representing the rows, columns of the matrix, and the given integer.
The following ‘N’ lines of input contain ‘M’ space-separated integers representing the matrix elements.
For each test case, print a single integer representing the minimum possible sum of all elements in each submatrix. Print the answer in the modulo 10^9 + 7.
Print a single line for each test case.
1 <= T <= 10
1 <= N, M <= 500
0 <= K <= 10^12
1<= mat[i][j] <= 10^6
Time Limit: 1 sec
In this approach, we will count the number of times a given element will count towards the cumulative submatrix sum for each element in the matrix. We will maintain the variables to count from top-left, top-right, bottom-left, bottom-right.
Then we sort the array in reverse order according to the count, and for each, we will subtract K and add it to the answer.
Algorithm: