AI工具人
提示词工程师

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;
}



赞(0) 打赏
未经允许不得转载:XINDOO » codeforces 289 B. Polo the Penguin and Matrix

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册