AcWing 1018. Minimum toll (linear DP)


Title Link

Title Description

A businessman goes through an n × N square grid, to participate in a very important business activity.
He should enter from the upper left corner of the grid and exit from the lower right corner.
It takes 1 unit of time for each small square in the middle.
The merchant must cross out within (2n − 1) unit time.
When passing through each small square in the middle, you need to pay a certain fee.
The businessman expected to cross out at the least cost within the specified time.
How much is the minimum charge?
Note: it is not allowed to cross each small square diagonally (that is, it can only move up, down, left, right and cannot leave the grid).

Topic model

  • Sub topic:Picking flowers
  • Because it takes (2n-1) units of time to cross (2n-1), and it takes (2n-1) units of time to walk from (1,1) to (n, n), you can’t go back.

Title code


using namespace std;

const int N = 110;

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

int main()
    cin >> n;
    for(int i = 1; i <= n; i ++ )
        for(int j = 1; j <= n; j ++ )
            cin >> w[i][j];
    memset(f, 0x3f, sizeof f);  // Because min is calculated, it is initialized to the maximum, and the boundary problem needs to be considered
    for(int i = 1; i <= n; i ++ )
        for(int j = 1; j <= n; j ++ )
            if(i == 1 && j == 1) f[i][j] = w[i][j];  // (1, 1) special judgment is required in the cycle, otherwise an error will occur
            else f[i][j] = min(f[i - 1][j], f[i][j - 1]) + w[i][j];

    cout << f[n][n] << endl;
    return 0;