(dp)acwing 1018. Minimum toll

1018. Minimum toll

Topic link

A businessman goes through a grid of N×N squares to participate in a very important business event.

He has to enter from the upper left corner of the grid and exit from the lower right corner.

It takes 1 unit of time to cross a small square in the middle.

The merchant must cross out in (2N-1) unit time.

And when passing through each small square in the middle, you need to pay a certain fee.

The merchant expects to cross out within the specified time with the least cost.

How much does it cost at least?

Note: You cannot cross each small square diagonally (that is, you can only move up, down, left, and right, and cannot leave the grid).

Input format The
first line is an integer, which represents the width N of the square.

In the next N rows, each row contains N integers not greater than 100, which is the cost of each small square on the grid.

Output format
Output an integer, indicating the minimum required cost.

Data range 1≤N≤100
Input example: 5 1 4 6 8 10 2 5 7 15 17 6 ​​8 9 18 20
10 11 12 19 21 20 23 25 29 33
Output example: 109 Sample explanation
example, the smallest The value is 109=1+2+5+7+9+12+19+21+33.

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int M = 0x3f3f3f3f;
int a[110][110];
int dp[110][110];
int main() {
    
    
	int n;
	cin >> n;
	memset(dp, M, sizeof(dp));
	for (int i = 1; i <= n; i++) {
    
    
		for (int j = 1; j <= n; j++) {
    
    
			cin >> a[i][j];
		}
	}
	for (int i = 1; i <= n; i++) {
    
    
		for (int j = 1; j <= n; j++) {
    
    
			if (i == 1 && j == 1)
			{
    
    
				dp[i][j] = a[i][j];
				continue;//注意
			}
			if (i > 1)
				dp[i][j] = min(dp[i - 1][j], dp[i][j]);
			if (j > 1)
				dp[i][j] = min(dp[i][j], dp[i][j - 1]);
			dp[i][j] += a[i][j];
		}
	}
	cout << dp[n][n];
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46028214/article/details/115220360