C++程式碼:計算使兩個陣列相同所需的操作次數


假設我們有兩個包含n個元素的陣列A和B。考慮一個操作:選擇兩個索引i和j,然後將第i個元素減少1,並將第j個元素增加1。執行操作後,陣列的每個元素必須是非負的。我們想要使A和B相同。我們必須找到使A和B相同的操作序列。如果不可能,則返回-1。

因此,如果輸入類似於A = [1, 2, 3, 4];B = [3, 1, 2, 4],則輸出將為[(1, 0), (2, 0)],因為對於i = 1和j = 0,陣列將為[2, 1, 3, 4],然後對於i = 2和j = 0,它將為[3, 1, 2, 4]

步驟

為了解決這個問題,我們將遵循以下步驟:

a := 0, b := 0, c := 0
n := size of A
Define an array C of size n and fill with 0
for initialize i := 0, when i < n, update (increase i by 1), do:
   a := a + A[i]
for initialize i := 0, when i < n, update (increase i by 1), do:
   b := b + A[i]
if a is not equal to b, then:
   return -1
Otherwise
   for initialize i := 0, when i < n, update (increase i by 1),
do:
   c := c + |A[i] - B[i]|
   C[i] := A[i] - B[i]
   c := c / 2
   i := 0
   j := 0
   while c is non-zero, decrease c after each iteration, do:
      while C[i] <= 0, do:
         (increase i by 1)
      while C[j] >= 0, do:
         (increase j by 1)
      print i and j
      decrease C[i] and increase C[j] by 1

示例

讓我們來看下面的實現以更好地理解:

#include <bits/stdc++.h>
using namespace std;
void solve(vector<int> A, vector<int> B){
   int a = 0, b = 0, c = 0;
   int n = A.size();
   vector<int> C(n, 0);
   for (int i = 0; i < n; i++)
      a += A[i];
   for (int i = 0; i < n; i++)
      b += A[i];
   if (a != b){
      cout << -1;
      return;
   }
   else{
      for (int i = 0; i < n; i++){
         c += abs(A[i] - B[i]);
         C[i] = A[i] - B[i];
      }
      c = c / 2;
      int i = 0, j = 0;
      while (c--){
         while (C[i] <= 0)
            i++;
         while (C[j] >= 0)
            j++;
         cout << "(" << i << ", " << j << "), ";
         C[i]--, C[j]++;
      }
   }
}
int main(){
   vector<int> A = { 1, 2, 3, 4 };
   vector<int> B = { 3, 1, 2, 4 };
   solve(A, B);
}

輸入

{ 1, 2, 3, 4 }, { 3, 1, 2, 4 }

輸出

(1, 0), (2, 0),

更新於:2022年3月15日

瀏覽量:186

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.