Problem Description
给定一个由n行数字组成的数字三角形如下图所示。试设计一个算法,计算出从三角形的顶至底的一条路径,使该路径经过的数字总和最大。
对于给定的由n行数字组成的数字三角形,计算从三角形的顶至底的路径经过的数字和的最大值。
Input
输入数据的第1行是数字三角形的行数n,1≤n≤100。接下来n行是数字三角形各行中的数字。所有数字在0..99之间。
Output
输出数据只有一个整数,表示计算出的最大值。
Sample Input
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Sample Output
30
#include<bits/stdc++.h>
using namespace std;
int d[120][120];
int a[120][120];
int n;
int main(){
cin>>n;
for(int i=1; i<=n; i++){
for(int j=1; j<=i; j++){
cin>>d[i][j];
}
}
for(int j=1; j<=n; j++){
a[n][j] = d[n][j];
}
for(int i=n; i>1; i--){
for(int j=1; j<=i; j++){
if(a[i][j] > a[i][j+1]){
a[i-1][j] = a[i][j] + d[i-1][j];
}
else{
a[i-1][j] = a[i][j+1] + d[i-1][j];
}
}
}
cout<<a[1][1]<<endl;
return 0;
}