Bark Beetles
Time limit1sMemory limit128 MB
Two beetles alternate taking one end picket or both end pickets from a row; each maximizes its own total, so find both final totals.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Game theory, Array, Greedy
- Solved
- No attempts yet
Problem
Two bark beetles have decided to devour an old wooden fence. The fence is a row of pickets whose heights are not necessarily equal. To make the meal more fun, the beetles turned it into a game and eat the pickets in alternating turns.
On its turn a beetle may either eat one of the two pickets currently at an end of the fence (the leftmost or the rightmost), or eat both end pickets at once. Each beetle always chooses so that the total height of the pickets it eats over the whole game is as large as possible.
The first beetle moves first. Determine how much wood each beetle ends up eating.
Input
The first line contains an integer (), the number of pickets.
The second line contains integers (), the heights of the pickets from left to right.
Output
Print two integers on a single line: first the total height of the pickets eaten by the beetle that starts the game, then the total height eaten by its opponent.
Note
Consider the fence . On the first turn the starting beetle can take the picket of height , the picket of height , or both ends at once. Eating the picket of height is optimal: the opponent then faces and eats both ends ( and ) at once, leaving for the starter. The starter eats and the opponent eats .