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;
    }
  • 相关阅读:
    类型初始值设定项引发异常的解决方法
    sql修改排序规则,区分大小
    SQLServer查询所有子节点
    Cannot resolve the collation conflict between "Chinese_PRC_CI_AS" and "SQL_L及由于排序规则不同导致查询结果为空的问题
    SQLServer跨库查询--分布式查询
    DataTable对象的操作问题
    .Net插入大批量数据
    SQL修改字段类型
    数据抓包分析
    Qss 皮肤
  • 原文地址:https://www.cnblogs.com/dealer/p/12381883.html
Copyright © 2011-2022 走看看