You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
1.3 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 55;
int n, m;
int w[N][N];
int f[N * 2][N][N];
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> w[i][j];
// 左上角是(1,1),k表示两个小朋友所在位置的x+y的和最多是n+m
for (int k = 2; k <= n + m; k++)
for (int x1 = 1; x1 <= n; x1++) // 第一个小朋友竖着走的距离
for (int x2 = 1; x2 <= n; x2++) { // 第二个小朋友竖着走的距离
int y1 = k - x1, y2 = k - x2; // 计算横着走的距离
// 不能出界,只走有效的位置
if (y1 < 1 || y1 > m || y2 < 1 || y2 > m) continue;
// 将本位置的数值加上
int &x = f[k][x1][x2];
x = max(x, f[k - 1][x1 - 1][x2] + w[x1][y1]);
x = max(x, f[k - 1][x1 - 1][x2 - 1] + w[x1][y1]);
x = max(x, f[k - 1][x1][x2 - 1] + w[x1][y1]);
x = max(x, f[k - 1][x1][x2] + w[x1][y1]);
// 如果不是重复的位置,还可以继续加上
if (x1 != x2) f[k][x1][x2] += w[x2][y2];
}
// 输出DP的结果
printf("%d\n", f[n + m][n][n]);
return 0;
}