Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

รหัส C++ เพื่อนับจำนวนการดำเนินการเพื่อให้สองอาร์เรย์เหมือนกัน


สมมติว่าเรามีสองอาร์เรย์ A และ B ที่มีจำนวนองค์ประกอบ n พิจารณาการดำเนินการ:เลือกสองดัชนี i และ j จากนั้นลดองค์ประกอบ ith ลง 1 และเพิ่มองค์ประกอบ jth ขึ้น 1 องค์ประกอบแต่ละองค์ประกอบของอาร์เรย์จะต้องไม่เป็นค่าลบหลังจากดำเนินการ เราต้องการสร้าง A และ Bsame เราต้องหาลำดับของการดำเนินการเพื่อให้ 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),