Editorial for WC '16 Contest 1 S3 - Tricky's Treats


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Tricky's time can be spent either walking between houses or visiting them for treats. The trade-off between spending more time walking to visit further-away houses versus having more time to visit more houses is difficult to manage. It will be much more manageable if we can fix the time spent on one of these two activities, and optimize for the other one.

After sorting the houses in increasing order of position, let's imagine that we'll decide that some house i will be the furthest house that Tricky will visit. This immediately fixes the amount of time that he'll spend on walking at 2P_i (he'll need to walk to position P_i and then back to position 0, and on the way he'll be able to freely visit any other houses closer than house i). This leaves M-2P_i time for visiting some subset of houses with indices from 1 to i.

This means that h_i = \lfloor \frac{M-2P_i}{T} \rfloor houses can be visited. Clearly then, of the first i houses, the h_i of them with the largest C values should be chosen (or all i houses if h_i \ge i). If we consider each possible house i separately, calculate h_i, and find the largest \min(i, h_i) C values out of C_{1 \dots i}, we can come up with an answer in \mathcal O(N^2 \log N) time.

This approach can be improved to \mathcal O(N \log N) time by noticing that the optimal set of houses for a given i can be computed more efficiently based on the optimal set of houses for i-1, rather than from scratch. We can iterate i upwards from 1 to N, while maintaining a priority queue of the current optimal C values as well as storing the sum of the values in this queue. When we reach a new house i, we can add C_i to the priority queue (and add C_i to its sum), and then we'll need to repeatedly pop the smallest value from the priority queue until it contains no more than h_i values (while similarly keeping the sum of these values up to date).

For convenience of implementation, we can negate all values stored in the priority queue to allow easy removal of its smallest value rather than its largest one. In this way, the priority queue will always store the largest \min(i, h_i) C values out of the first i values (as well as their sum), with their sum being the optimal number of treats which can be collected assuming that house i is the furthest house visited, and as such being a candidate for the final answer.


Comments

There are no comments at the moment.