您的位置:首页 > 产品设计 > UI/UE

B. Polo the Penguin and Matrix

2013-09-04 09:32 549 查看
time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

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

Sample test(s)

input
2 2 2
2 4
6 8


output
4


input
1 2 7
6 7


output
-1


解题说明:此题意思是对矩阵中的元素进行加减一个常量d,让矩阵中每个元素值相同,问最少需要进行多少次加减操作。显然,如果矩阵中的元素除以d的余数不相同,那么无论多少次加减都不可能让所有数相等。在余数相同的情况下,可以对矩阵中的元素进行排序,以中间的数为基准,小的数加d,大的数减d,遍历统计即可。

#include <iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
using namespace std;

int a[1000010];

int main()
{
int sum,n,m,d,r,w,i;
scanf("%d %d %d",&n,&m,&d);
sum=n*m;
scanf("%d",&a[0]);
r=a[0]%d;
for(i=1;i<sum;i++)
{
scanf("%d",&a[i]);
if(a[i]%d!=r)
{
printf("-1\n");
return 0;
}
}
sort(a,a+sum);
r=a[sum/2];
w=0;
for(i=0;i<sum;i++)
{
w+=abs(a[i]-r)/d;
}
printf("%d\n",w);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: