一个人从(1,1)走到(n,m),一个人从(n,1)走到(1,m)。这两条路径只能有一个格子相同,且这个格子的值不算。
问你这两个路径经过的值总和最大是多少。
POINT:
四个角分别dp。遍历每一个相同格子来做。她们两个人经过相同格子时的方向肯定是垂直的,不然不满足条件。
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
const int maxn = 1e3+5;
int dp1[maxn][maxn], dp2[maxn][maxn], dp3[maxn][maxn], dp4[maxn][maxn], a[maxn][maxn];
int main()
{
int n,m;
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
scanf("%d",&a[i][j]);
}
}
//dp1---(1,1)到(i,j)的最大值
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
dp1[i][j]=max(dp1[i-1][j],dp1[i][j-1])+a[i][j];
}
}
//dp2---(i,j)到(n,m)的最大值
for(int i=n;i>=1;i--){
for(int j=m;j>=1;j--){
dp2[i][j]=max(dp2[i+1][j],dp2[i][j+1])+a[i][j];
}
}
//dp3---(n,1)到(i,j)的最大值
for(int i=n;i>=1;i--){
for(int j=1;j<=m;j++){
dp3[i][j]=max(dp3[i+1][j],dp3[i][j-1])+a[i][j];
}
}
//dp4---(i,j)到(1,m)的最大值
for(int i=1;i<=n;i++){
for(int j=m;j>=1;j--){
dp4[i][j]=max(dp4[i-1][j],dp4[i][j+1])+a[i][j];
}
}
int ans=0;
for(int i=2;i<=n-1;i++){
for(int j=2;j<=m-1;j++){
ans=max(ans,dp1[i-1][j]+dp2[i+1][j]+dp3[i][j-1]+dp4[i][j+1]);
ans=max(ans,dp1[i][j-1]+dp2[i][j+1]+dp3[i+1][j]+dp4[i-1][j]);
}
}
printf("%d\n",ans);
}