dp
dp[i][j]表示(1,1)-(i,j)小矩阵的最大收获,可以轻松得到dp方程:
dp[i][j] = max( dp[i][j-1] + col[j][i], dp[i-1][j] + row[i][j]);
其中row[i][j]表示第i行从第0列到j列的和,col[i][j]表示第i列从第0行到j行的和。
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 500 + 5;
int n, m;
int data_x[MAXN][MAXN];
int data_y[MAXN][MAXN];
int d[MAXN][MAXN] = {};
int row[MAXN][MAXN];
int col[MAXN][MAXN];
int main(){
while(true){
//输入
scanf("%d %d", &n, &m);
if(n == 0)
return 0;
memset(d, 0, sizeof(int) * MAXN * MAXN);
memset(row, 0, sizeof(int) * MAXN * MAXN);
memset(col, 0, sizeof(int) * MAXN * MAXN);
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
scanf("%d", &data_x[i][j]);
row[i][j] = row[i][j-1] + data_x[i][j];
}
}
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
scanf("%d", &data_y[i][j]);
col[i][j] = col[i-1][j] + data_y[i][j];
}
}
//……
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
d[i][j] = d[i-1][j] + row[i][j];
if(d[i][j] < d[i][j-1] + col[i][j])
d[i][j] = d[i][j-1] + col[i][j];
}
}
printf("%d\n", d[n][m]);
}
return 0;
}