Editorial for WC '16 Contest 1 S3 - Tricky's Treats
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 will be the furthest house that Tricky will visit. This immediately fixes the amount of time that he'll spend on walking at (he'll need to walk to position and then back to position , and on the way he'll be able to freely visit any other houses closer than house ). This leaves time for visiting some subset of houses with indices from to .
This means that houses can be visited. Clearly then, of the first houses, the of them with the largest values should be chosen (or all houses if ). If we consider each possible house separately, calculate , and find the largest values out of , we can come up with an answer in time.
This approach can be improved to time by noticing that the optimal set of houses for a given can be computed more efficiently based on the optimal set of houses for , rather than from scratch. We can iterate upwards from to , while maintaining a priority queue of the current optimal values as well as storing the sum of the values in this queue. When we reach a new house , we can add to the priority queue (and add to its sum), and then we'll need to repeatedly pop the smallest value from the priority queue until it contains no more than 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 values out of the first values (as well as their sum), with their sum being the optimal number of treats which can be collected assuming that house is the furthest house visited, and as such being a candidate for the final answer.
Comments