CF - William and Robot

Authors: Alex Du, Benjamin Qi

Table of Contents

ExplanationImplementation

Explanation

First note that the only requirement for a valid solution is that for any even number knk \leq n, William must have selected at most k2\frac{k}{2} integers out of the first kk integers. It is impossible to select more than k2\frac{k}{2} integers in the first kk integers, since the robot will have taken all other k2\frac{k}{2} 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 k2\frac{k}{2} integers for k<nk < n, allowing you to choose more for a larger kk.

For example, if we had array of size 44, we could select either of the first two elements and either of the last two elements, selecting exactly k2\frac{k}{2} integers for both k=2k = 2 and k=4k = 4. Alternatively, we could select both of the last two elements, selecting 0 integers for k=2k = 2 and 22 integers for k=4k = 4. 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 kk from 11 to nn and maintain a priority queue of the numbers tentatively selected by William so far. For each kk we push aka_k to the priority queue, and then if kk is even, pop the smallest element of the priority queue while the number of taken integers is greater than k/2k/2.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N \log N)

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!