题目传送门
$f_{i,j,1/0}$表示到$(i,j)$从上面/下面来的最大值. 则方程为 :(f_{i,j,1}=max) { (f_{i-1,j,1},f_{i-1,j,0},f_{i,j-1,1})}
(f_{i,j,1}=max) { (f_{i-1,j,1},f_{i-1,j,0},f_{i,j+1,0})}
发现i会有后效性,那就将j放在外层循环.
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
long long n,m,a[1005][1005],f[1005][1005][2];
inline long long mx() {
long long s = 0,w = 1;
char ch = getchar();
while(ch < '0' || ch > '9') {
if(ch == '-') w = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9') {
s = s * 10 + (ch - '0');
ch = getchar();
}
return s * w;
}
int main() {
n = mx();
m = mx();
memset(f,0x80,sizeof(f));
for(int i = 1;i <= n; i++)
for(int j = 1;j <= m; j++)
a[i][j] = mx();
f[1][1][0] = f[1][1][1] = a[1][1];
for(int j = 1;j <= m; j++) {
for(int i = 1;i <= n; i++)
if(i != 1 || j != 1) f[i][j][1] = max(f[i][j-1][0],max(f[i][j-1][1],f[i-1][j][1])) + a[i][j];
for(int i = n;i >= 1; i--)
if(i != 1 || j != 1) f[i][j][0] = max(f[i][j-1][0],max(f[i][j-1][1],f[i+1][j][0])) + a[i][j];
}
printf("%lld",max(f[n][m][1],f[n][m][0]));
return 0;
}