Files
python/TangDou/AcWing/NumberTriangles/275.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

38 lines
1.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}