Editorial for TLE '16 Contest 4 P1 - Stack of Presents


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.

Author: ZQFMGB12

We can solve this problem using a greedy algorithm. First, sort the presents in non-decreasing order of weight. Then, iterate through the presents while keeping track of the cumulative weight so far. If the current present's weight is not less than the cumulative weight, add it to the stack.

The proof of the greedy algorithm is as follows:

For the sake of contradiction, assume that the greedy solution is not optimal.

The greedy solution selects presents g_1, g_2, \dots, g_x.

The optimal solution selects the lightest presents o_1, o_2, \dots, o_y.

There is a maximal value of r such that g_1 = o_1, g_2 = o_2, \dots, g_r = o_r, g_{r+1} \ne o_{r+1}, \dots

Since g_{r+1} is both a valid choice and has a smaller weight than o_{r+1}, o_{r+1} can be replaced by g_{r+1} without worsening our answer. Now, g_{r+1} = o_{r+1} and thus, there is a contradiction in the choice of o.

Time complexity: \mathcal{O}(N \log N)


Comments

There are no comments at the moment.