CF - William and Robot
Authors: Alex Du, Benjamin Qi
Explanation
First note that the only requirement for a valid solution is that for any even number , William must have selected at most integers out of the first integers. It is impossible to select more than integers in the first integers, since the robot will have taken all other integers by the time you can choose your next integer. Note that it is also possible to "save" your choices, since you can choose less than integers for , allowing you to choose more for a larger .
For example, if we had array of size , we could select either of the first two elements and either of the last two elements, selecting exactly integers for both and . Alternatively, we could select both of the last two elements, selecting 0 integers for and integers for . Note that we cannot take both the first and second element, since the Robot will take the one we don't pick.
To solve this problem, we can iterate from to and maintain a priority queue of the numbers tentatively selected by William so far. For each we push to the priority queue, and then if is even, pop the smallest element of the priority queue while the number of taken integers is greater than .
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;int main() {int n;cin >> n;vector<int> a(n);for (int &i : a) { cin >> i; }
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!