The Triangle
7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 (Figure 1)
Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100.
The numbers in the triangle, all integers, are between 0 and 99.
Your program is to write to standard output. The highest sum is written as an integer.
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
30
自己做出的第一个dp;
coed:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
int tri[102][102];
int dp[102][102];
int n;
cin >> n;
int i,j;
for(i = 1; i <= n; i++){
for(j = 1; j <= i; j++){
cin >> tri[i][j];
}
}
memset(dp,0,sizeof(dp));
for(i = 1; i <= n; i++){
for(j = 1; j <= i; j++){//当前值加上上一个状态的最大的
dp[i][j] = tri[i][j] + max(dp[i-1][j],dp[i-1][j-1]);
}
}
int maxsum = 0;
for(i = 1; i <= n; i++){
if(dp[n][i] > maxsum)
maxsum = dp[n][i];
}
cout << maxsum << endl;
return 0;
}
本文介绍了一个经典的动态规划问题——寻找给定三角形中从顶点到底部的最大路径和。通过递推公式,自底向上计算每个节点所能达到的最大路径和,并最终找出所有路径中的最大值。
455

被折叠的 条评论
为什么被折叠?



