AcWing 275. 传纸条
原题链接
中等
作者:
松鼠爱葡萄
,
2020-10-02 16:45:16
,
所有人可见
,
阅读 415
因为
1 <= i <= n, 1 <= k - i <= m
所以
i <= k - 1, i >= k - m;
max(1, k - m) <= i <= min(k - 1, n);
f[k][x1][x2] = max(f[k][x1][x2], f[k - 1][x1][x2] + t);
f[k - 1][x1 - 1][x2]
f[k - 1][x1][x2 - 1]
f[k - 1][x1 - 1][x2 - 1]
所以可以写成a, b两层循环
for (int a = 0; a < 2; a++) {
for (int b = 0; b < 2; b++) {
f[k][x1][x2] = max(f[k][x1][x2], f[k - 1][x1 - a][x2 - b] + t);
}
}
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 55;
int f[N * 2][N][N], w[N][N];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> w[i][j];
}
}
for (int k = 2; k <= n + m; k++) {
for (int x1 = max(1, k - m); x1 <= min(k - 1, n); x1++) {
for (int x2 = max(1, k - m); x2 <= min(k - 1, n); x2++) {
int t = w[x1][k - x1];
if (x1 != x2) t += w[x2][k - x2];
for (int a = 0; a < 2; a++) {
for (int b = 0; b < 2; b++) {
f[k][x1][x2] = max(f[k][x1][x2], f[k - 1][x1 - a][x2 - b] + t);
}
}
}
}
}
cout << f[n + m][n][n] << endl;
}