基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题
收藏
关注
取消关注
一个高度为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
设dp[i][j]表示以第i行第j列为终点的方案的经过的数字的最大值。
状态转移方程:dp[i][j]=max{dp[i-1][j-1],dp[i-1][j]}+a[i][j].
边界条件:dp[1][1]=a[1][1].
1 #include <iostream> 2 #include <algorithm> 3 #include <cstring> 4 using namespace std; 5 int a[505][505]; 6 int dp[505][505]s; 7 int main() 8 { 9 int n; 10 cin>>n; 11 memset(a,0,sizeof(a)); 12 memset(dp,0,sizeof(dp)); 13 for(int i=1;i<=n;i++) 14 for(int j=1;j<=i;j++) 15 { 16 cin>>a[i][j]; 17 } 18 dp[1][1]=a[1][1]; 19 for(int i=2;i<=n;i++) 20 for(int j=1;j<=i;j++) 21 { 22 dp[i][j]=max(max(dp[i][j],dp[i-1][j-1]+a[i][j]),dp[i-1][j]+a[i][j]); 23 } 24 int ans=0; 25 for(int i=1;i<=n;i++) 26 ans=max(ans,dp[n][i]); 27 cout<<ans<<endl; 28 return 0; 29 }