n개의 요소가 있는 두 개의 배열 A와 B가 있다고 가정합니다. 연산을 고려하십시오. 두 개의 인덱스 i와 j를 선택한 다음 i번째 요소를 1만큼 줄이고 j번째 요소를 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),