acwing 1027. square access
https://www.acwing.com/problem/content/1029/
For walking once, the state transition equation is easy to obtain: $ f [i] [j] = max (f [i-1] [j], f [i] [j-1]) + w [i] [j] $.
And for two walks, set the state to $ f [i_1] [j_1] [i_2] [j_2] $ means the first path goes from $ (1, 1) $ to $ (i_1, j_1) $ The maximum sum of the two paths from $ (1, 1) $ to $ (i_2, j_2) $.
The core of this question is: how to deal with the same grid can not be taken twice. The analysis shows that only when $ i_1 + j_1 = i_2 + j_2 $, the grid can be the same grid, which also inspired us to reduce the state by one dimension.
Use $ k = i_1 + j_1 = i_2 + j_2 $, so that the state becomes $ f [k] [i_1] [i_2] $.
1 #include <iostream> 2 #include <algorithm> 3 4 using namespace std; 5 6 const int N = 15; 7 8 int n; 9 int w[N][N]; 10 int f[N * 2][N][N]; 11 12 int main() 13 { 14 cin >> n; 15 16 int a, b, c; 17 while (cin >> a >> b >> c, a || b || c) w[a][b] = c; 18 19 for (int k = 2; k <= n + n; k ++ ) 20 for (int i1 = 1; i1 <= n; i1 ++ ) 21 for (int i2 = 1; i2 <= n; i2 ++ ) 22 { 23 int j1 = k - i1, j2 = k - i2; 24 if (j1 >= 1 && j1 <= n && j2 >= 1 && j2 <= n) 25 { 26 int t = w[i1][j1]; 27 if (i1 != i2) t += w[i2][j2]; 28 int &x = f[k][i1][i2]; 29 x = max(x, f[k - 1][i1 - 1][i2 - 1] + t); 30 x = max(x, f[k - 1][i1 - 1][i2] + t); 31 x = max(x, f[k - 1][i1][i2 - 1] + t); 32 x = max(x, f[k - 1][i1][i2] + t); 33 } 34 } 35 36 cout << f[n + n][n][n] << endl; 37 return 0; 38 }