C++で行列のすべての要素を等しくするための特定の型の最小演算
問題の説明
整数KとMxNの行列が与えられた場合、タスクは、行列のすべての要素を等しくするために必要な操作の最小数を見つけることです。 1回の操作で、行列の任意の要素に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
-
C++を使用して2つの文字列を等しくするために必要な特定の操作の最小数。
問題の説明 2つの文字列str1とstr2がある場合、両方の文字列に文字「a」と「b」が含まれます。両方の文字列は同じ長さです。両方の文字列に1つの_(空のスペース)があります。タスクは、次の操作の最小数を実行することにより、最初の文字列を2番目の文字列に変換することです- _が位置Iにある場合、_は位置i+1またはi-1の文字と交換できます 位置i+1とi+2の文字が異なる場合、_は位置i+1またはi+2の文字と交換できます 同様に、位置i-1とi-2の文字が異なる場合、_は位置i-1またはi-2の文字と交換できます str1 =“ aba_a”およびstr2 =“
-
C++で配列のすべての要素を同じにするための最小限の削除操作。
問題の説明 要素が繰り返されるようなn個の要素の配列が与えられます。配列から任意の数の要素を削除できます。タスクは、配列から削除する要素の最小数を見つけて、配列を等しくすることです。 arr[] = {10, 8, 10, 7, 10, -1, -4, 12} すべての配列要素を同じにするには、強調表示された5つの要素を削除する必要があります。 アルゴリズム 1. Count frequency of each element 2. Find maximum frequecy among the frequencies. Let us call this as maxFrequncy 3.