This page is still under construction.

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

Line of Bentham

Time limit1sMemory limit256 MB

Summary
Replace some people in a line with agents so the total happiness, where each person sums likes over the three ahead, is maximized.
Level

Medium7 of 10

Topics
Dynamic programming, Greedy
Solved
No attempts yet

Problem

N people stand in a line facing forward. The front person is number 1 and the back person is number N.

Each person distinguishes at most the 3 people directly ahead. For person ii and person jj, the integer pi,jp_{i,j} records how much ii likes jj and lies from −10-10 to 1010. The happiness of person ii is qi=pi,i−3+pi,i−2+pi,i−1q_i = p_{i,i-3} + p_{i,i-2} + p_{i,i-1}. When j≤0j \le 0, define pi,j=0p_{i,j} = 0. The total happiness is Q=∑i=1NqiQ = \sum_{i=1}^{N} q_i.

Any positions in the line may be replaced with dispatched agents. An agent has happiness 00 and does not affect the happiness of people behind. There is no limit on the number of agents.

Compute the maximum total happiness obtainable from the N people.

Input

The first line gives the number of people NN with 3≤N≤1,000,0003 \le N \le 1,000,000.

The next NN lines describe each person. The line for person ii gives three integers pi,i−3p_{i,i-3}, pi,i−2p_{i,i-2} and pi,i−1p_{i,i-1}.

When j≤0j \le 0, the value pi,jp_{i,j} is given as 00. All other pi,jp_{i,j} are integers from −10-10 to 1010.

Output

Print the maximum total happiness obtainable after replacing some people with agents.

Hint

In the public sample input, keeping everyone gives happiness values 00, 22, −3-3 and 11 for a total of 00. Replacing persons 11 and 22 with agents gives 0+0+0+2=20 + 0 + 0 + 2 = 2, and no replacement reaches a larger total.

Examples1

  1. Example 1

    Input
    4
    0 0 0
    0 0 2
    0 -1 -2
    0 -1 2
    
    Expected output
    2