AcWing 898. 数字三角形
作者:互联网
题目链接
题目思路
这道题我们可以从最底层考虑,若要使当前路径之和最大,选择当前的所选值加左上/右上之和最大即可
因为有负数情况,所以要把边界设置好
题目代码
#include <iostream>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 510;
int a[N][N], f[N][N];
int n;
int main()
{
cin >> n;
for(int i = 1; i <= n; i ++ )
for(int j = 1; j <= i; j ++ )
cin >> a[i][j];
for(int i = 0; i <= n; i ++ )
for(int j = 0; j <= i + 1; j ++ )
f[i][j] = -INF;
f[1][1] = a[1][1];
for(int i = 2; i <= n; i ++ )
for(int j = 1; j <= i;j ++ )
f[i][j] = max(f[i - 1][j - 1] + a[i][j], f[i - 1][j] + a[i][j]);
int res = -INF;
for(int i = 1; i <= n; i ++ )
res = max(res, f[n][i]);
cout << res << endl;
return 0;
}
标签:www,题目,右上,898,int,const,三角形,include,AcWing 来源: https://www.cnblogs.com/vacilie/p/16106386.html