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

 

a[i] % d = (a[i]+d) % d = (a[i]-d) % d

取中位数所得绝对值的差值最小

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <set>
#include <queue>
#include <map>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <numeric>
#include <cmath>
#include <unordered_set>
#include <unordered_map>
//#include <xfunctional>
#define ll long long
#define mod 998244353
using namespace std;
int dir[4][2] = { {0,1},{0,-1},{-1,0},{1,0} };
const long long INF = 0x7f7f7f7f7f7f7f7f;
const int inf = 0x3f3f3f3f;

int main()
{
    int n, m, d, res = 0;
    cin >> n >> m >> d;
    int k = m*n;
    vector<int> a(k);
    for (int i = 0; i < k; i++)
        cin >> a[i];
    int mid = k / 2;
    sort(a.begin(), a.end());
    for (int i = 0; i < k; i++)
    {
        if (a[mid] % d != a[i] % d)
        {
            cout << -1;
            return 0;
        }
        res += abs(a[mid] - a[i]) / d;
    }
    cout << res;
    return 0;
}

 

posted @ 2020-02-29 11:03  DeaL57  阅读(183)  评论(0编辑  收藏  举报