Editorial for Baltic OI '09 P2 - Candy Machine
Submitting an official solution before solving the problem yourself is a bannable offence.
A first, simple approach is to use dynamic programming over the wagon positions. This would lead to a run time of
When looking for a better solution, we observe that the paths of two wagons never need to cross. Two crossing paths can be replaced by two paths with the parts after the crossing exchanged. Then, we have a "smallest" wagon, i.e. a wagon such that there is no candy with a smaller position than any of the candies caught by that wagon. Now assume we can compute an optimal smallest wagon path (OSWP) such that this wagon catches as many candies as possible. Afterwards, we disregard all candies caught by the smallest wagon, compute the OSWP for the remaining candies, and so on. If the computation of the OSWP can be done in
Indeed, it is possible to compute an OSWP in
A more efficient algorithm builds upon the idea of non-crossing paths, too, but passes candies by position. Each candy is to be assigned to the leftmost possible wagon. If binary search is used to determine the wagon and a balanced tree is used to store each wagon's candies, a run time of
Further improvements may even yield a runtime of
Comments