用 C++ 使矩陣的所有元素相等所需的最小操作


問題陳述

給定一個整數 K 和一個 M x N 的矩陣,任務是找出使矩陣所有元素相等所需的最小運算元。在單次操作中,K 可以被新增到或從矩陣的任何元素中減去。

示例

If input matrix is:
{
   {2, 4},
   {20, 40}
} and K = 2 then total 27 operations required as follows;
Matrix[0][0] = 2 + (K * 9) = 20 = 9 operations
Matrix[0][1] = 4 + (k * 8) = 20 = 8 operations
Matrix[1][0] = 20 + (k * 10) = 40 = 10 operations

演算法

1. Since we are only allowed to add or subtract K from any element, we can easily infer that mod of all the elements with K should be equal. If it’s not, then return -1
2. sort all the elements of the matrix in non-deceasing order and find the median of the sorted elements
3. The minimum number of steps would occur if we convert all the elements equal to the median

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
int getMinOperations(int n, int m, int k, vector<vector<int> >& matrix) {
   vector<int> arr(n * m, 0);
   int mod = matrix[0][0] % k;
   for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
         arr[i * m + j] = matrix[i][j];
            if (matrix[i][j] % k != mod) {
               return -1;
            }
      }
   }
   sort(arr.begin(), arr.end());
   int median = arr[(n * m) / 2];
   int minOperations = 0;
   for (int i = 0; i < n * m; ++i)
      minOperations += abs(arr[i] - median) / k;
   if ((n * m) % 2 == 0) {
      int newMedian = arr[(n * m) / 2];
      int newMinOperations = 0;
      for (int i = 0; i < n * m; ++i)
         newMinOperations += abs(arr[i] - newMedian) / k;
      minOperations = min(minOperations, newMinOperations);
   }
   return minOperations;
}
int main() {
   vector<vector<int> > matrix = {
      { 2, 4},
      { 20, 40},
   };
   int n = matrix.size();
   int m = matrix[0].size();
   int k = 2;
   cout << "Minimum required operations = " <<
   getMinOperations(n, m, k, matrix) << endl;
   return 0;
}

當你編譯並執行以上程式時。它會生成以下輸出

輸出

Minimum required operations = 27

更新日期:23-Dec-2019

241 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告