D - Reindeer and Sleigh Editorial by en_translator
Swapping the indices of sleighs does not change the answer, so we assume that \((R_1,R_2, \ldots, R_N)\) are sorted in ascending order.
When choosing \(m\) sleighs under this assumption, we can assume that sleighs \(1,2,\ldots, m\) are chosen, so this problem is boiled down to finding the maximum \(m\) such that \(R_1 + R_2 + \ldots + R_m \leq X\).
This can be found by precalculating the cumulative sum, i.e. the values \(R_1 + R_2 + \ldots + R_i\) for all \(i\), and performing a binary search against the resulting sequence.
Sorting the sequence costs \(O(N \log N)\) time, and each query costs \(O(\log N)\) time, so this problem can be solved in a total of \(O((N+Q) \log N)\) time.
In this problem, you can prefetch the queries, so you can sort the queries in ascending order of \(X\), and find the answer using a sliding window.
Sample code
#include <iostream>
#include <vector>
#include <algorithm>
#define rep(i, n) for (ll i = 0; i < (n); i++)
using namespace std;
using ll = long long;
int main() {
int n, q;
cin >> n >> q;
vector<ll> r(n);
rep(i, n) cin >> r[i];
sort(r.begin(), r.end());
vector<ll> s(n + 1);
rep(i, n) s[i + 1] = s[i] + r[i];
while (q--) {
ll x;
cin >> x;
cout << upper_bound(s.begin(), s.end(), x) - s.begin() - 1 << endl;
}
}
posted:
last update: