acwing 1027 grid access (digital triangle model)

Topic

Insert picture description here

Problem solution (digital triangle model)

  1. Linear DP, digital triangle model, extension of the peanuts question, we know that if it is to go from A to B once, then directly f[i] [j] = max( f[i-1] [j], f[i] [j-1]) + w[i] [j] Consider the maximum value transferred from the top or the right of the point with coordinates (i, j), but this problem requires walking twice, and the first The value of the point that has been traversed will become 0. Of course, we can’t calculate it twice, because the maximum value of the two paths is not necessarily equal to the maximum value of the two paths.
  1. We can take two paths at the same time. f[i1][j1][i2][j2] means all the paths from (1,1)(1,1) to (i1,j1), (i2,j2) The maximum value, because the two paths start from the point (1,1) at the same time, all the steps taken are the same, that is, k = i1 + j1 = i2 + j2, so we change the equation into a three-dimensional f[k ][i1][j2]

Insert picture description here

  1. We can divide the state into 2 (bottom right in the first step) * 2 (bottom right in the second step) = 4, but if the two steps go to the same grid, the value will only be added once.

Code

#include<bits/stdc++.h>

using namespace std;
const int N = 11;

int n;
int w[N][N];
int f[2 * N][N][N];

int main() {
    
    

    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    cin >> n;
    int a, b, c;
    while (cin >> a >> b >> c, a || b || c) {
    
    
        w[a][b] = c;
    }

    for (int k = 2; k <= n + n; k++) {
    
    
        for (int i1 = 1; i1 <= k; i1++) {
    
    
            for (int i2 = 1; i2 <= k; i2++) {
    
    
                int j1 = k - i1, j2 = k - i2;
                if (j1 >= 1 && j1 <= n && j2 >= 1 && j2 <= n) {
    
    
                    int val = w[i1][j1];
                    if (i1 != i2) val += w[i2][j2];
                    f[k][i1][i2] = max(f[k][i1][i2], f[k - 1][i1 - 1][i2 - 1] + val);
                    f[k][i1][i2] = max(f[k][i1][i2], f[k - 1][i1][i2 - 1] + val);
                    f[k][i1][i2] = max(f[k][i1][i2], f[k - 1][i1 - 1][i2] + val);
                    f[k][i1][i2] = max(f[k][i1][i2], f[k - 1][i1][i2] + val);
                }
            }
        }
    }

    cout << f[n + n][n][n] << endl;

    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/115086878