Cow Pinball

Interview

Time limit1sMemory limit128 MB

Summary
Given a triangle of nail scores with R rows, find the maximum sum along a path from the top nail down to the last row, moving to one of the two adjacent nails below each step.
Level

Medium4 of 10

Topics
Dynamic programming, Array, Matrix, Recursion
Solved
No attempts yet

Problem

The cows are playing a game called pachinko. You drop a ball in at the top, and as it falls it strikes nails, veering a little to the left or right, until it comes out at the bottom.

This pachinko machine is special. The ball always strikes the single top nail of the RR rows of nails (1≤R≤251 \le R \le 25), and then hits either the left or right nail just below it. From there it again falls to the left or right nail just below, and this repeats all the way down to the last row. The ball never veers too far — no more than half a nail — from the nail it just struck.

Scoring is unusual too: you earn points XijX_{ij} (0≤Xij≤30000 \le X_{ij} \le 3000) for every nail you strike on the way down. The cows want to maximize their score. What is the highest score they can achieve?

Here is an example triangle and a good route; the nails marked with * form the path.

                    7                        *7
                  3   8                    *3   8
                8   1   0                *8   1   0
              2   7   4   4             2  *7   4   4
            4   5   2   6   5         4  *5   2   6   5

In the example above, the route 7→3→8→7→57 \to 3 \to 8 \to 7 \to 5 gives the highest sum, 3030. Going from 77 to 88 and then to 88 again is impossible: the 88 in the third row is too far away.

Input

  • Line 1: a single integer RR.
  • Lines 2 to R+1R+1: line i+1i+1 contains the ii space-separated scores of the ii-th row of the machine: Xi1,Xi2,…,XiiX_{i1}, X_{i2}, \dots, X_{ii}.

Output

  • Line 1: a single integer, the maximum achievable score.

Examples3

  1. Example 1

    Input
    5
    7
    3 8
    8 1 0
    2 7 4 4
    4 5 2 6 5
    
    Expected output
    30
    
  2. Example 2

    Input
    1
    42
    
    Expected output
    42
    
  3. Example 3

    Input
    3
    7
    3 8
    8 1 0
    
    Expected output
    18