题目:
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
题解:
简单的动态规划问题;
状态:f[i][j]表示从顶到i行j列得到的最大值;
状态转移方程:f[i][j] = max(f[i - 1][j], f[i - 1][j -1 ]) + a[i][j];
注意边界就行了;
代码:
#include<cstdio>
using namespace std;
int main()
{
int N,a[103][103],f[103][103],i,j,m=0;
scanf("%d",&N);
for(i=0;i<N;i++)
for(j=0;j<=i;j++)
scanf("%d",&a[i][j]);
f[0][0]=a[0][0];
for(i=1;i<N;i++)
for(j=0;j<=i;j++)
if(j==0) f[i][j]=f[i-1][j]+a[i][j]; //边界设置
else if(j==i) f[i][j]=f[i-1][j-1]+a[i][j]; //边界设置
else f[i][j]=a[i][j]+(f[i-1][j]>f[i-1][j-1]?f[i-1][j]:f[i-1][j-1]); //递推实现
for(i=N-1,j=0;j<=i;j++)
if(f[i][j]>m) m=f[i][j]; //寻找最大值
printf("%d",m);
return 0;
}