Search for a command to run...
Progressive hints first, then the full explanation and implementation when you're ready to cash out.
Review status
AI-generated and still unreviewed. Double-check the details before internalizing them.
Hints
Open only as much as you need to keep the solve alive.
For each index, forget “swap” for a second. You are just choosing which of the two numbers goes into , and the other automatically goes into .
Let be the number you choose to put in . Since the pair sum is fixed, the objective becomes
Rewrite it as a fixed total minus something:
So you want to minimize , i.e. the sum of all chosen -values except the biggest one. One value gets a free pass. Cute little scam.
Every chosen is at least . If the maximum chosen value is at index , then
To make this as small as possible, you want the excluded to be as large as possible.
The optimal move is simply: put into array and into array for every . Then
For each index , after optionally swapping, exactly one of the two numbers goes into , and the other goes into .
Let be the value chosen for . Then the value placed in is . The objective is
The pair sums are fixed, so this is
The first term is constant. Therefore, maximizing the answer is the same as minimizing
That expression is just the sum of all chosen -values except the largest one. One chosen value gets ignored. That is the whole trick.
Define
No matter what we choose, we always have
Suppose the maximum chosen occurs at index . Then
So the penalty can never be smaller than .
Now choose
for every index. In plain English: put the smaller number of each pair into , and the larger number into .
Then
and
This exactly matches the lower bound, so it is optimal. No need for some fake complicated greedy. The best greedy is just “smaller upstairs, bigger downstairs.”
Therefore the answer is
We scan the arrays once per test case.
The memory can be beyond storing one array, but storing is already perfectly fine for . Use long long, because the answer can be around .
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void setIO() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
int main() {
setIO();
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<ll> a(n);
for (ll &x : a) cin >> x;
ll sumMax = 0;
ll bestMin = 0;
for (int i = 0; i < n; i++) {
ll b;
cin >> b;
sumMax += max(a[i], b);
bestMin = max(bestMin, min(a[i], b));
}
cout << sumMax + bestMin << '\n';
}
return 0;
}#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void setIO() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
int main() {
setIO();
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<ll> a(n);
for (ll &x : a) cin >> x;
ll sumMax = 0;
ll bestMin = 0;
for (int i = 0; i < n; i++) {
ll b;
cin >> b;
sumMax += max(a[i], b);
bestMin = max(bestMin, min(a[i], b));
}
cout << sumMax + bestMin << '\n';
}
return 0;
}