Polo the Penguin and Matrix

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 aij.

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.

Input

The first line contains three integers nm 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 aij (1 ≤ aij ≤ 104).

Output

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).

Examples
input
Copy
2 2 2
2 4
6 8
output
Copy
4
input
Copy
1 2 7
6 7
output
Copy
-1 
Problem solution: Seeing that the data is relatively small, I ran it violently.
 1 #pragma warning(disable:4996)
 2 #include<cmath>
 3 #include<string>
 4 #include<cstdio>
 5 #include<cstring>
 6 #include<iostream>
 7 #include<algorithm>
 8 using namespace std;
 9 
10 const int maxn = 10005;
11 
12 int n, m, d;
13 int a[maxn];
14 
15 int main()
16 {
17     while (cin >> n >> m >> d) {
18         int cnt = 0, ma = 0;
19         for (int i = 1; i <= n; i++) {
20             for (int j = 1; j <= m; j++) {
21                 int tp;
22                 scanf("%d", &tp);
23                 a[++cnt] = tp;
24                 ma = max(ma, tp);
25             }
26         }
27         int ans = 2000000007;
28         for (int i = 1; i <= ma; i++) {
29             int tem = 0;
30             bool flag = true;
31             for (int j = 1; j <= cnt; j++) {
32                 if (abs(a[j] - i) % d) { flag = false; break; }
33                 tem += abs(a[j] - i) / d;
34             }
35             if (flag) ans = min(ans, tem);
36         }
37         if (ans == 2000000007) cout << "-1" << endl;
38         else cout << ans << endl;
39     }
40     return 0;
41 }
 
   

 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325313553&siteId=291194637