cf 402bPolo the Penguin and Matrix

来源:互联网 发布:2016网络原创歌曲比赛 编辑:程序博客网 时间:2024/06/05 02:26

这个矩阵,看题啊,题目中说如果矩阵已经是相等的了,就是不需要移动,还有就是一开始以为是一个等差数列才可以,后来一想不需要,鬼知道样例是啥,去了一开始的一个等差数列的判断就对了

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 mfrom left to right. Let's represent the matrix element on the intersection of row iand 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).

Example
Input
2 2 22 46 8
Output
4
#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <algorithm>#include <vector>#include <map>#include <math.h>#include <stack>#define LL long longusing namespace std;const int INF = 0x3f3f3f3f;const int maxn = 100+10;int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};int g[maxn * maxn];int d;int m,n;int main(){    int flag = 0;    int flag1 = 1;    int cur = 0;    scanf("%d%d%d",&m,&n,&d);    for(int i = 0; i < m*n; i++)    {        scanf("%d",&g[i]);    }    sort(g,g + n*m);        int mid = m*n / 2 ;        for(int i = 0; i < m*n; i++)        {            if(abs(g[i] - g[mid]) % d != 0)            {                flag = 1;                break;            }            else            {                 cur+=abs(g[i] - g[mid]) / d;            }        }        if(flag)        {            printf("-1\n");        }        else            printf("%d\n",cur);    return 0;}


原创粉丝点击