Editorial for COCI '11 Contest 5 #2 Eko


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.

A naive solution is to try all possible sawblade heights, from lowest to highest or vice versa, until the correct height is found. We can simply try a height value by iterating over all trees and summing the cut-off parts. This algorithm has complexity \mathcal O(N * max\_height), which is too slow.

A faster solution can be obtained by reducing the number of heights that we need to try. Let us assume that we have tried out a height of H', cutting off less than M metres of wood. This result implies that the needed height H is less than H'. Conversely, if by cutting at a height of H'' we obtained at least M metres of wood, the needed height H must be greater than or equal H''.

The natural algorithm to apply here is binary search: we keep the upper and lower bound of the possible height interval, and in each step we try a height H' in the middle of that interval and, depending on the result, reduce the search interval to the upper or lower half.

The problem can also be solved by sorting the tree heights from highest to lowest, setting the cutoff height to the highest tree height and gradually lowering it to the height of each lower tree until cutting off at least M metres of wood. Detailed analysis of this approach is left as an exercise to the reader.


Comments

There are no comments at the moment.