Editorial for Facebook Hacker Cup '17 Qualifying Round P2 - Lazy Loading


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.

Consider the heaviest item that hasn't yet been moved. When this item is moved, it should certainly be on the top of the stack to make the current bag appear as heavy as possible. To move this item, we'll need to add as many other items as necessary to make the bag appear to weigh at least 50 pounds.

This leads us to the following greedy solution: At every step, put the heaviest available item (with weight W) in the bag, along with the K lightest available items, where K is the lowest integer that satisfies (K+1) \times W \ge 50. If there aren't enough remaining items to fake a 50-pound bag, then you can't complete another trip. Pretend that you put those items in the last bag moved.

To efficiently find the heaviest and lightest items, we should first sort the input. This takes \mathcal O(N \log N) time, and the rest of the algorithm takes \mathcal O(N) time. (Given the small bound on the weights of the items, a more efficient sorting method is possible, but unnecessary.)


Comments

There are no comments at the moment.