F - Minimum Glutton Editorial by en_translator
Consider the following Problem A and Problem B:
Problem A:
He arrange the \(N\) dishes in any order and eat them in that order. He stops eating when the total sweetness exceeds \(X\). What is the minimum number of dishes he ends up eating?
Problem B:
He arrange the \(N\) dishes in any order and eat them in that order. He stops eating when the total saltiness exceeds \(Y\). What is the minimum number of dishes he ends up eating?
For a fixed arrangement of the dishes, once the condition that he stops eating is satisfied, the condition in Problem A or Problem B is satisfied; if the condition in Problem A or Problem B is satisfied, that of the original problem is satisfied.
By the former fact, \(\min\) (answer to Problem A, answer to Problem B) \(\leq\) (answer to the original problem) follows; by the latter fact, (answer to the original problem) \(\leq\) (answer to Problem A, answer to Problem B) follows. Thus, the answer to the original problem equals the minimum value of the answers to Problem A and Problem B.
Therefore, it is sufficient to solve Problem A and B. If you sort them in descending order of \(A_i\) and \(B_i\), respectively, eating them from the first in order is an optimal strategy to achieve the minimum value.
Sample code
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ll n, x, y;
cin >> n >> x >> y;
vector<ll> a(n), b(n);
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < n; i++) cin >> b[i];
sort(a.begin(), a.end(), greater<>());
sort(b.begin(), b.end(), greater<>());
int c1 = 0, c2 = 0;
ll sx = 0, sy = 0;
for (int i = 0; i < n; i++) {
sx += a[i];
c1++;
if (sx > x) break;
}
for (int i = 0; i < n; i++) {
sy += b[i];
c2++;
if (sy > y) break;
}
cout << min(c1, c2) << '\n';
}
posted:
last update: