This page is still under construction.

Parts of this page are still being built. What you see may change.

Stacking Balls

Interview

Time limit1sMemory limit128 MB

Summary
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 11 ball, the next row holds 22, and so on, so row ii holds ii balls. The ball in row ii, column jj 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 i−1i-1, namely (i−1, j−1)(i-1,\ j-1) and (i−1, j)(i-1,\ j).

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 (1, 1)(1,\ 1) 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 00.

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 NN, the number of rows the balls are stacked in (1≤N≤10001 \le N \le 1000). Each of the following NN lines describes one row: line ii contains the integers Bi1, Bi2, …, BiiB_{i1},\ B_{i2},\ \dots,\ B_{ii} separated by spaces (−105≤Bij≤105-10^5 \le B_{ij} \le 10^5, 1≤j≤i≤N1 \le j \le i \le N), where BijB_{ij} is the integer written on the ball in row ii, column jj. (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 00, marking the end of the input.

Output

For each test case, print on its own line the maximum score the contestant can obtain.

Examples4

  1. Example 1

    Input
    4
    3
    -5 3
    -8 2 -8
    3 9 -2 7
    2
    -2
    1 -10
    3
    1
    -5 3
    6 -4 1
    0
    
    Expected output
    7
    0
    6
    
  2. Example 2

    Input
    1
    5
    0
    
    Expected output
    5
    
  3. Example 3

    Input
    1
    -7
    0
    
    Expected output
    0
    
  4. Example 4

    Input
    3
    1
    2 3
    4 5 6
    0
    
    Expected output
    21