#d1807. 矩阵操作

矩阵操作

Matrix Operation

Problem Source

Click here

Problem Description

There is an n×mn \times m integer matrix AA, where each number is in the range [0,k)[0, k).

In one operation, you may perform one of the following two types:

  1. For any row ii, change every number Ai,tA_{i, t} in that row to (Ai,t+1) mod k(A_{i, t} + 1) \bmod k.
  2. For any column jj, change every number At,jA_{t, j} in that column to (At,j+1) mod k(A_{t, j} + 1) \bmod k.

Given n,m,k,An, m, k, A, determine whether AA can be turned into the all-zero matrix by several such operations. If yes, output the minimum number of operations; otherwise output −1-1.

Input Format

One line with three integers 1≤n≤20001 \le n \le 2000, 1≤m≤20001 \le m \le 2000, 1≤k≤1091 \le k \le 10^9.

The next nn lines each contain mm numbers, representing the initial state of matrix AA.

Output Format

One line: if possible, output the number of operations; otherwise output −1-1.

Sample Input 1

3 3 10
0 0 9
0 0 9
9 9 8

Sample Output 1

2

Sample Input 2

3 3 10
1 0 9
0 0 9
9 9 8

Sample Output 2

-1

Constraints

1≤n≤20001 \le n \le 2000, 1≤m≤20001 \le m \le 2000, 1≤k≤1091 \le k \le 10^9.