codeforces 289 B. Polo the Penguin and Matrix

题目链接

题目意思是在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;
}



原文地址:https://www.cnblogs.com/xindoo/p/3595132.html