Description
如下图左边所示为一个数字三角形,也叫数塔
请编一个程序计算从顶到底的某处的一条路径,使该路径所经过的数字总和最大。只要求输出总和。
1.一步可沿左斜线向下或右斜线向下走;
2.三角形行数小于等于100;
3.三角形中的数字为0,1,…,99;
一个n层的数塔对应的输入为n+1行,如下图右边所示格式,第1行为数塔层数,第2行到第n+1行为各层的数字。
Input
输入为n+1行的数字,意义见题目描述
Output
输出为一个整数,即题意所述最大的那个路径数字总和
Sample Input 1
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Sample Output 1
30
#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;
const int N = 110;
int arr[N][N];
int f[N][N];
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= i; j++) cin >> arr[i][j];
for (int i = n; i >= 1; i--)
for (int j = 1; j <= i; j++)
f[i][j] = max(f[i + 1][j], f[i + 1][j + 1]) + arr[i][j];
cout << f[1][1];
return 0;
}