传送门
走两次
dp[x1][y1][x2][y2]表示两条路分别到两个点的坐标后的最大值
为了防止走重,dp[x1][y1][x1][y1]赋值为无穷小
时间复杂度O(n^4)
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=60;
int a[N][N],dp[N][N][N][N];
int m,n;
int max4(int a,int b,int c,int d){return max(a,max(b,max(c,d)));
}
int main(){scanf("%d%d",&n,&m);for(int i=1;i<=n;i++){for(int j=1;j<=m;j++) scanf("%d",&a[i][j]);}for(int x1=1;x1<=n;x1++){for(int y1=1;y1<=m;y1++){for(int x2=1;x2<=n;x2++){for(int y2=1;y2<=m;y2++){if(x1==x2&&y1==y2&&(x1!=n||y1!=m)) dp[x1][y1][x2][y2]=-2e9;else{dp[x1][y1][x2][y2]=max4(dp[x1-1][y1][x2-1][y2]+a[x1][y1]+a[x2][y2],dp[x1-1][y1][x2][y2-1]+a[x1][y1]+a[x2][y2],dp[x1][y1-1][x2-1][y2]+a[x1][y1]+a[x2][y2],dp[x1][y1-1][x2][y2-1]+a[x1][y1]+a[x2][y2]);}}}}}printf("%d",dp[n][m][n][m]);
}
/*
3 3
0 3 9
2 8 5
5 7 0
*/
优化
用k表示走的步数
dp[k][y1][y2]表示两条路径走到的点纵坐标分别为y1y2
那么横坐标分别为k-y1+2,k-y2+2
注意横坐标也必须在1到m的范围内
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=60;
int a[N][N],dp[2*N][N][N];
int m,n;
int max4(int a,int b,int c,int d){return max(a,max(b,max(c,d)));
}
int main(){scanf("%d%d",&n,&m);for(int i=1;i<=n;i++){for(int j=1;j<=m;j++) scanf("%d",&a[i][j]);}for(int k=1;k<=n+m-2;k++){for(int y1=1;y1<=m;y1++){if(k-y1+2<1||k-y1+2>n) continue;for(int y2=1;y2<=m;y2++){if(k-y2+2<1||k-y2+2>n){continue;}if(y1==y2&&(y1!=m||k-y1+2!=n)) dp[k][y1][y2]=-2e9;else dp[k][y1][y2]=max4(dp[k-1][y1][y2],dp[k-1][y1-1][y2-1],dp[k-1][y1-1][y2],dp[k-1][y1][y2-1])+a[k-y1+2][y1]+a[k-y2+2][y2];}}}printf("%d",dp[n+m-2][m][m]);
}
/*
3 3
0 9 9
6 1 8
2 3 0
*/
心得
本题之前做过,但仍然不耽误忘
主要是没有想到赋值成无穷小的方法以去除决策
学废了