Luogu P1004-Grid Access

Title description

There is an N×N grid (N≤9), we fill some of the squares with a positive integer, and other squares with the number 0. As shown in the figure below (see example):
A
0 0 0 0 0 0 0 0 0
0 0 13 0 0 6 0 0
0 0 0 0 7 0 0 0
0 0 0 14 0 0 0 0
0 21 0 0 0 4 0 0
0 0 15 0 0 0 0 0
0 14 0 0 0 0 0 0
0 0 0 0 0 0 0 0 B

Someone starts from point A in the upper left corner of the picture and can walk down or to the right until he reaches point B in the lower right corner. On the way he is walking, he can take the number in the square (the square after taking it will become the number 0).
This person walks twice from point A to point B. Try to find two such paths so that the sum of the obtained numbers is the largest. The first line of the input format is an integer N (representing an N×N grid), and each subsequent line has three integers. The first two indicate the position, and the third number is the number placed at that position. A single line of 00 indicates the end of input. The output format only needs to output an integer, representing the largest sum obtained on 22 paths.

Sample input and output

Input
8
2 3 13
2 6 6
3 5 7
4 4 14
5 2 21
5 6 4
6 3 15
7 2 14
0 0 0
Output
67
Explanation/Prompt NOIP 2000 Improvement Group 4th question

It is worth noting that the max function is to find the largest of the four parameters, but when using the max function in four-dimensional DP,
there is a little recursive meaning an[i][j][b][k] refers to the first time to reach [i][j] point and the second time to reach [b][k] point is the maximum harvest point.

#include<stdio.h>
int max(int a, int b, int c, int d)
{
    
    
 if (a < b) a = b;
 if (a < c) a = c;
 if (a < d) a = d;
 return a;
}
int main()
{
    
    
 int shu[10][10] = {
    
     0 }, an[10][10][10][10] = {
    
     0 }, term = 0;
 int n = 0, a = 0, b = 0, c = 0;
 scanf("%d", &n); getchar();
 scanf("%d %d %d", &a, &b, &c);
 for (; a != 0 || b != 0 || c != 0;)
 {
    
    
  shu[a][b] = c; scanf("%d %d %d", &a, &b, &c); getchar();
 }
 for (int i = 1; i <= n; i++) 
  for (int j = 1; j <= n; j++) 
   for (int b = 1; b <= n; b++) 
    for (int k = 1; k <= n; k++)
    {
    
    
     an[i][j][b][k] = max(an[i - 1][j][b - 1][k], an[i - 1][j][b][k - 1], an[i][j - 1][b - 1][k], an[i][j - 1][b][k - 1])+ (shu[i][j] + shu[b][k]) / ((i == b && j == k) ? 2 : 1);
    }
 printf("%d", an[n][n][n][n]);
 return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46091928/article/details/107860378