c ++ dynamic programming (dp)
Title Description
Watch out for the number of towers. Write a program to find the path from the highest point in the end the end of the section any position to make a path through the numbers and maximum.
Each step can go to the lower left corner from the current point, you can also reach a point lower right corner.
Entry
5
13
11 8
12 7 26
6 14 15 8
12 7 13 24 11
Export
86
AC Code
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 505;
int dp[MAXN][MAXN],a[MAXN][MAXN];
int max(int a,int b)//max函数求两个数字之间的最大值
{
return a>b?a:b;
}
int main()
{
int n;
cin >> n;
for (int i = 1;i <= n;i ++)//输入
{
for (int j = 1;j <= i;j ++)
{
cin >> a[i][j];
}
}
dp[1][1] = a[1][1];//把起点直接放在dp[]里面
for (int i = 2;i <= n;i ++)
{
for (int j = 1;j <= i;j ++)
{
dp[i][j] = max(dp[i - 1][j - 1],dp[i - 1][j]) + a[i][j];//dp公式,原理是先走一步,然后扫描这个点的上一层的邻接点看看哪个点的dp值最大,然后用最大值加上他本身
}
}
int ans = 0;
for (int i = 1;i <= n;i ++)
{
ans = max(ans,dp[n][i]);//ans的作用是在最底部的元素中找一个最大的dp,输出
}
cout << ans << endl;
return 0;
}