총 n과 m 값이 각각 있는 두 개의 배열과 b가 있다고 가정합니다. 두 배열의 값을 사용하여 n 또는 m개의 쌍(둘 중 최소값)을 만들어야 합니다. 쌍은 배열의 값과 배열 b의 다른 값을 포함해야 합니다. 쌍의 값의 차이가 최소이고 동일하도록 쌍을 만들어야 합니다. 값을 출력으로 인쇄합니다.
따라서 입력이 n =4, m =4, a ={2, 3, 4, 7}, b ={3, 4, 6, 5}인 경우 출력은 1이 됩니다.
만들 수 있는 쌍은 -
(3, 4), (4, 5), (7, 6), (2, 3).
모든 쌍의 값 차이는 1입니다.
단계
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
sort the array a Define an array s1 initialized with 0 Define an array s2 initialized with 0 for initialize i := 1, when i < n, update i := i + 2, do: insert last element of s1 + a[i] - a[i - 1] at the end of s1 for initialize i := 2, when i < n, update i := i + 2, do: insert last element of s2 + a[i] - a[i - 1] at the end of s2 ans := infinity for each value w in b, do: diff := first element in the array a not less than w - first value of a sub := last element of s1[diff / 2] + s2 ans := minimum of ans and sub print(ans)
예시
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
void solve(int n, int m, vector<int> a, vector<int> b){
sort(a.begin(), a.end());
vector<int> s1 = {0};
vector<int> s2 = {0};
for (int i = 1; i < n; i += 2)
s1.push_back(a[i] - a[i - 1] + s1.back());
for (int i = 2; i < n; i += 2)
s2.push_back(a[i] - a[i - 1] + s2.back());
int ans = INF;
for (const auto & w : b) {
int diff = lower_bound(a.begin(), a.end(), w) - a.begin();
int sub = s1[diff / 2] + s2.back() - s2[diff / 2] + abs(a[diff / 2 * 2] - w);
ans = min(ans, sub);
}
cout << ans << endl;
}
int main() {
int n = 4, m = 4;
vector<int> a = {2, 3, 4, 7}, b = {3, 4, 6, 5};
solve(n, m, a, b);
return 0;
} 입력
4, 4, {2, 3, 4, 7}, {3, 4, 6, 5} 출력
1