Little penguin Polo has an *n* × *m* matrix, consisting of integers. Let's index the matrix rows from 1 to *n* from top to bottom and let's index the columns from 1 to *m* from left to right. Let's represent the matrix element on the intersection of row *i* and column *j* as *a*<sub class="lower-index">*ij*</sub>.

In one move the penguin can add or subtract number *d* from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
The first line contains three integers *n*, *m* and *d* (1 ≤ *n*, *m* ≤ 100, 1 ≤ *d* ≤ 10<sup class="upper-index">4</sup>) — the matrix sizes and the *d* parameter. Next *n* lines contain the matrix: the *j*-th integer in the *i*-th row is the matrix element *a*<sub class="lower-index">*ij*</sub> (1 ≤ *a*<sub class="lower-index">*ij*</sub> ≤ 10<sup class="upper-index">4</sup>).
import math
n,m,d = map(int,input().split(" "))
flag,min_operations,ops,arr = False,math.inf,[0] * (n * m),[]
for i in range(n):
    arr += list(map(int,input().split(" ")))            # matrix -> 1D array cast
for x in range(len(arr)):
    for i in range(x + 1,len(arr)):
        temp = abs(arr[x] - arr[i])
        if temp % d != 0:
            flag = True
            break
        ops[x] += temp // d                     # 0 -> 1
        ops[i] += temp // d                     # 1 -> 0
    min_operations = min(min_operations,ops[x])
if flag:
    print(-1)
else: print(min_operations)

''' 
possible or impossible:
difference between one number and every single other one in matrix 
should be divisible by 'd'. If any number without this divisibility 
exist in matrix, we cannot reach it from other numbers by adding d or substructing d (n times), or 
get from this number to something else. So if we have such number, it's impossible to make
her equal to others. So at least one number like that -> impossible.

solution:
brute force: O((k^2 + k) / 2) k = nm : 
After we input the matrix, we can count total operations for two numbers at one iteration.
Ex: (2) + 2 = 4 -> store. AND (4) - 2 = 2 -> store.
count steps to equalize to every single cell, and choose the least.
During every single count, check whether difference is divisible by d, if not: break, imposssible.


Choose closest to average val. (maybe working)
O(3 * (n * m))




'''
