题意:
7
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.
思路:由底向上递推即可
代码:
思路:由底向上递推即可
代码:
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
const int maxn = 105;
int a[maxn][maxn];
int dp[maxn][maxn];
int main()
{
int n;
while (cin >> n) {
memset(a, 0, sizeof(a));
memset(dp, 0, sizeof(dp));
for (int i = 1 ; i<= n; ++i ){
for (int j = 1;j <= i; ++j) {
cin >> a[i][j];
}
}
for (int i = 1 ; i <= n; ++i) {
dp[n][i] = a[n][i];
}
for (int i = n - 1; i > 0; --i) {
for (int j = 1; j <= i; ++j) {
dp[i][j] = max(dp[i + 1][j], dp[i + 1][j + 1]) + a[i][j];
}
}
cout << dp[1][1] << endl;
}
}