https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1002
一个高度为N的由正整数组成的三角形,从上走到下,求经过的数字和的最大值。
每次只能走到下一层相邻的数上,例如从第3层的6向下走,只能走到第4层的2或9上。
5
8 4
3 6 9
7 2 9 5
例子中的最优方案是:5 + 8 + 6 + 9 = 28
Input
第1行:N,N为数塔的高度。(2 <= N <= 500)
第2 - N + 1行:每行包括1层数塔的数字,第2行1个数,第3行2个数......第k+1行k个数。数与数之间用空格分隔(0 <= A[i] <= 10^5) 。
Output
输出最大值
Input示例
4
5
8 4
3 6 9
7 2 9 5
Output示例
28
动态规划
#include<iostream>
#include<string.h>
#include<algorithm>
#include<vector>
#include<stdio.h>
#include<map>
#include<math.h>
#include<stack>
#define inf 0x3f3f3f
#define ll long long
#define maxn 505
using namespace std;
int a[maxn][maxn];
int dp[maxn][maxn];
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
dp[i][0]=0;
for(int j=1;j<=i;j++)
{
cin>>a[i][j];
dp[0][j]=0;
}
}
int maxx=0,j;
for(int i=1;i<=n;i++)
{
for( j=1;j<=n;j++)
{
dp[i][j]=max(dp[i-1][j],dp[i-1][j-1])+a[i][j];
maxx=max(maxx,dp[i][j]);
}
// maxx=max(maxx,dp[i][j]);
//cout<<dp[i][j]<<endl;
}
cout<<maxx<<endl;
return 0;
}