289B.md (1302B)
1 Source: https://codeforces.com/problemset/problem/289/B 2 3 B. Polo the Penguin and Matrix 4 5 time limit per test 6 7 2 seconds 8 9 memory limit per test 10 11 256 megabytes 12 13 input 14 15 stdin 16 17 output 18 19 stdout 20 21 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**ij*. 22 23 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. 24 25 Input 26 27 The first line contains three integers *n*, *m* and *d* (1 ≤ *n*, *m* ≤ 100, 1 ≤ *d* ≤ 104) — 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**ij* (1 ≤ *a**ij* ≤ 104). 28 29 Output 30 31 In a single line print a single integer — the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes). 32 33 Examples 34 35 Input 36 37 ``` 38 2 2 2 39 2 4 40 6 8 41 ``` 42 43 Output 44 45 ``` 46 4 47 ``` 48 49 Input 50 51 ``` 52 1 2 7 53 6 7 54 ``` 55 56 Output 57 58 ``` 59 -1 60 ```