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
个人思路:
从底层往上求值,通过动态规划,可以确定每一层各个数的最大值,第n层是其本身, 第n-1层第j个数能达到的最大值为其本身加max(第n层第j数能达到的最大值,第n数第j+1数能达到的最大值),依次往上求能达到的最大值。
示例代码:
#include <iostream>
#include <algorithm>
#define MAX 101
using namespace std;
int main()
{
int num[MAX][MAX];
int i, j;
int n;
cin >> n;
for(i=0; i<n; i++)
{
for(j=0; j<=i; j++)
{
cin >> num[i][j];
}
}
for(i=n-2; i>=0; i--)
{
for(j=0; j<=i; j++)
{
num[i][j] += max(num[i+1][j], num[i+1][j+1]);
}
}
cout << num[0][0] << endl;
return 0;
}