51nod 1084 矩阵取数问题 V2
递归式:
if x1 != x2 | dp[step + 1][x1][x2] = max{dp[step][x1’][x2’]} + a[x1][y1] + a[x2][y2]
if x1 == x2 | dp[step + 1][x1][x2] = max{dp[step][x1’][x2’]} + a[x1][y1]。
使用step减少空间使用
如图:
初始值:
dp[0][x][y] = 0;
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
#define LL long long
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define E 2.71828
#define MOD 1000000007
#define N 210
#define M 5010
int n,m;
int p[N][N];
int dp[N*2][N][N];
int main()
{
scanf("%d%d",&m,&n);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
scanf("%d",&p[i][j]);
memset(dp,0,sizeof(dp));
for(int k = 1; k < n+m; k++)
{
for(int i = 1; i<=n && i<=k; i++)
{
for(int j = 1; j<=n && j<=k; j++)
{
dp[k][i][j]=max(dp[k][i][j],dp[k-1][i-1][j-1]+p[i][k-i+1]+(i==j?0:p[j][k-j+1]));
dp[k][i][j]=max(dp[k][i][j],dp[k-1][i-1][j]+p[i][k-i+1]+(i==j?0:p[j][k-j+1]));
dp[k][i][j]=max(dp[k][i][j],dp[k-1][i][j-1]+p[i][k-i+1]+(i==j?0:p[j][k-j+1]));
dp[k][i][j]=max(dp[k][i][j],dp[k-1][i][j]+p[i][k-i+1]+(i==j?0:p[j][k-j+1]));
//printf("dp[%d][%d][%d] = %d\n",k,i,j,dp[k][i][j]);
}
}
}
printf("%d\n",dp[n+m-1][n][n]);
return 0;
}