The Triangle
Description
7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 (Figure 1)
Input
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.
Output
Your program is to write to standard output. The highest sum is written as an integer.
Sample Input
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Sample Output
30题目大意:给出一个数字三角形,自顶向下找出一条路径,使得路径上的数字相加之后得到的和最大。
解题思路:经典的动态规划问题,定义dp[i][j]为自底向上的路径中到a[i][j]的最大值,则dp[i][j] = max(dp[i + 1][j + 1],dp[i + 1][j]) + a[i][j],最后打印dp[0][0]的值即可。
代码如下:
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 105;
int dp[maxn][maxn],a[maxn][maxn];
int main()
{
int t,n,i,j,k,l;
while(scanf("%d",&n) != EOF){
memset(dp,0,sizeof(dp));
for(j = 0;j < n;j++)
for(k = 0;k <= j;k++)
scanf("%d",&a[j][k]);
for(j = 0;j < n;j++)
dp[n][j] = a[n][j];
for(j = n - 1;j >= 0;j--)
for(k = 0;k <= j;k++)
dp[j][k] = max(dp[j + 1][k],dp[j + 1][k + 1]) + a[j][k];
printf("%d\n",dp[0][0]);
}
return 0;
}