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.