题目

Description

The cows don't use actual bowling balls when they go bowling. They each take a number (in the range 0..99), though, and line up in a standard bowling-pin-like triangle like this:

7

3 8

8 1 0

2 7 4 4

4 5 2 6 5
Then the other cows traverse the triangle starting from its tip and moving "down" to one of the two diagonally adjacent cows until the "bottom" row is reached. The cow's score is the sum of the numbers of the cows visited along the way. The cow with the highest score wins that frame.

Given a triangle with N (1 <= N <= 350) rows, determine the highest possible sum achievable.

Input

Line 1: A single integer, N

Lines 2..N+1: Line i+1 contains i space-separated integers that represent row i of the triangle.

Output

Line 1: The largest sum achievable using the traversal rules

Sample Input

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

Sample Output

30

Hint

Explanation of the sample:

7
*

3 8
*

8 1 0
*

2 7 4 4
   *

4 5 2 6 5
The highest score is achievable by traversing the cows as shown above.

题解

非常明显的dp+贪心

对于n行的三角形,其一共有 n*(n+1)/2 个数

dp[left(i)] = max{ dp[left(i) , dp[i] + a[left(i)] }

dp[left(i+1)+1] = max{ dp[left(i)+1] , dp[i] + a[left(i)+1] }

其中,left(i)表示i下一层左边的数

代码

/*
By:OhYee
Github:OhYee
HomePage:http://www.oyohyee.com
Email:oyohyee@oyohyee.com
Blog:http://www.cnblogs.com/ohyee/

かしこいかわいい?
エリーチカ!
要写出来Хорошо的代码哦~
*/

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
using namespace std;

//DEBUG MODE
#define debug 0

//循环
#define REP(n) for(int o=0;o<n;o++)

#define t(n) (((n) * ((n)+1))/2)

const int maxn = 1005;
int n;
int a[t(maxn)];
int dp[t(maxn)];

int left(int n) {
    int i;
    for(i = 0;t(i) < n;i++);
    return n + i;
}

bool Do() {
    if(scanf("%d",&n) == EOF)
        return false;
    for(int i = 1;i <= t(n);i++)
        scanf("%d",&a[i]);

    memset(dp,0,sizeof(dp));
    for(int i = 0;i <= t(n - 1);i++) {
        dp[left(i)] = max(dp[left(i)],dp[i] + a[left(i)]);
        dp[left(i) + 1] = max(dp[left(i) + 1],dp[i] + a[left(i) + 1]);
    }

    int Max = -1;
    for(int i = t(n - 1) + 1;i <= t(n);i++)
        Max = max(Max,dp[i]);

    printf("%d\n",Max);
    return true;
}

int main() {
    while(Do());
    return 0;
}