zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    Google搜索引擎如何运作:不会手动调整结果
    一个Ruby脚本
    IE灭绝!?
    除Windows之外的其他操作系统
    刚收到的新书
    奇怪的计算机语言
    小巧的menuetOS
    Ruby学习笔记(1)
    一个通知
    总结 asp.net 和 javascript获取本地IP(MAC)和服务器IP(MAC)的方法
  • 原文地址:https://www.cnblogs.com/dealer/p/12381883.html
Copyright © 2011-2022 走看看