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

codeforces 289 B. Polo the Penguin and Matrix

2013-06-04 17:11 393 查看
题目链接

题目意思是在n*m的矩阵中,你可以对矩阵中的每个数加或者减d,求最少的操作次数,使得矩阵中所有的元素相同。

虽然在condeforces中被分到了dp一类,但完全可以通过排序,暴力的方法解决。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std;
const int maxn = 10005;
int a[maxn];

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