Stacking Balls
InterviewTime limit1sMemory limit128 MB
Pick balls from a triangular pile, where each ball needs both balls above it picked first, to maximize the total score; stopping early is allowed.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Greedy, Implementation, Math
- Solved
- No attempts yet
Problem
KDK Broadcasting has created a new game show. A contestant makes a series of choices, and the prize depends on those choices.
Balls are stacked in the shape of a triangle, and each ball has a single integer written on it. The top row holds ball, the next row holds , and so on, so row holds balls. The ball in row , column rests on the two balls directly beneath it, and the balls resting directly on top of it are the (at most two) balls of row , namely and .
The contestant may pick balls one at a time, and the score is the sum of the numbers on the picked balls. Picking a ball removes it from the triangle. A higher score wins a better prize. However, a ball may be picked only once every ball resting on top of it has already been picked. The topmost ball has nothing on top of it, so it can always be picked first. At any moment the contestant may choose to keep picking or to stop; if no ball is picked at all, the score is .
Program director Dong-gyu Kim wants to know the maximum score a contestant can obtain. What is that maximum?
Input
The input consists of several test cases. The first line of each test case contains , the number of rows the balls are stacked in (). Each of the following lines describes one row: line contains the integers separated by spaces (, ), where is the integer written on the ball in row , column . (The first row is the topmost row, and the first ball of each row is the leftmost ball.)
The last line of the input contains a single , marking the end of the input.
Output
For each test case, print on its own line the maximum score the contestant can obtain.