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;
    }
  • 相关阅读:
    Future和Callable的使用
    Tiny Jpeg Decoder (JPEG解码程序) 源代码分析 1:解码文件头
    jQuery 表格排序插件 Tablesorter 使用
    jQuery 表单验证插件 jQuery Validation Engine 使用
    jQuery 文本编辑器插件 HtmlBox 使用
    开源视频质量评价工具: IQA
    hql 语法与详细解释
    MYSQL常用命令
    C++发送HTTP请求获取网页HTML代码
    编译运行Red5源代码
  • 原文地址:https://www.cnblogs.com/dealer/p/12381883.html
Copyright © 2011-2022 走看看