• Polo the Penguin and Matrix


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

    Examples
    input
    Copy
    2 2 2
    2 4
    6 8
    output
    Copy
    4
    input
    Copy
    1 2 7
    6 7
    output
    Copy
    -1

    a[i] % d = (a[i]+d) % d = (a[i]-d) % d

    取中位数所得绝对值的差值最小

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <string>
    #include <set>
    #include <queue>
    #include <map>
    #include <sstream>
    #include <cstdio>
    #include <cstring>
    #include <numeric>
    #include <cmath>
    #include <unordered_set>
    #include <unordered_map>
    //#include <xfunctional>
    #define ll long long
    #define mod 998244353
    using namespace std;
    int dir[4][2] = { {0,1},{0,-1},{-1,0},{1,0} };
    const long long INF = 0x7f7f7f7f7f7f7f7f;
    const int inf = 0x3f3f3f3f;
    
    int main()
    {
        int n, m, d, res = 0;
        cin >> n >> m >> d;
        int k = m*n;
        vector<int> a(k);
        for (int i = 0; i < k; i++)
            cin >> a[i];
        int mid = k / 2;
        sort(a.begin(), a.end());
        for (int i = 0; i < k; i++)
        {
            if (a[mid] % d != a[i] % d)
            {
                cout << -1;
                return 0;
            }
            res += abs(a[mid] - a[i]) / d;
        }
        cout << res;
        return 0;
    }
  • 相关阅读:
    PPP协议 PAP认证
    交换机广播风暴,STP生成树协议,端口聚合
    传统远程注入线程,加载DLL
    EXE和DLL调用关系,DLL制作,钩子
    window bat批处理 实用脚本
    python利用scapy嗅探流量
    关于AWD线下攻防的经验
    APP 仿微信登录
    价值1500左右的毕业设计都开源啦
    EOS2.0环境搭建-centos7
  • 原文地址:https://www.cnblogs.com/dealer/p/12381883.html
Copyright © 2020-2023  润新知