#P4078. [SDOI2016] 探险路线

[SDOI2016] 探险路线

Description

The jungle you face can be modeled as a grid with nn rows and mm columns. The cell in row ii and column jj represents a region. Each cell has an integer weight v(i,j)v(i,j) (possibly negative), representing the gain or cost of visiting that region. Each cell can be visited at most once, and you may not go outside the grid. You are required to start from the cell in the first row and first column, and finish at the cell in the nn-th row and mm-th column. Your goal is to maximize the sum of the weights of all visited cells.

Because of certain reasons, your expedition route is subject to some restrictions. Initially you are at the start. Then, on each day, you must first choose one direction among up, down, left, and right, and move 00 steps (i.e., do not move) or any number of steps along this direction; after that, choose a direction again (it can be the same as before or different), and keep moving along that direction until you reach some boundary position of the grid, ending that day's expedition. The expedition can last for any number of days. The boundary position where a day's expedition ends will be the starting position of the next day, unless that day is the end of the expedition. Note that, because each cell can be visited at most once and your final ending point must be at position (n,m)(n,m), you need to plan each day's route carefully.

You want to know, under the optimal plan, how large the total gain of the entire expedition can be, that is, the maximum possible sum of the weights of all visited cells.

Input Format

The first line contains two integers, representing the total number of rows nn and the total number of columns mm. Then follow nn lines, each containing mm integers. The integer in row ii and column jj corresponds to the gain or cost of visiting the region at row ii and column jj.

Output Format

Output a single integer, the sum of the weights of all visited cells in an optimal expedition route.

10 10
+1 +1 +1 +1 +1 -1 -1 -1 -1 -1
-1 -1 +1 +1 +1 -1 -1 -1 -1 -1
-1 -1 +1 +1 +1 +1 +1 +1 +1 +1
+1 +1 +1 +1 -1 -1 -1 -1 -1 +1
+1 -1 -1 +1 -1 -1 -1 -1 -1 +1
+1 +1 +1 +1 -1 -1 -1 -1 -1 +1
+1 +1 +1 +1 +1 +1 +1 +1 +1 +1
+1 -1 -1 -1 -1 -1 -1 -1 -1 -1
+1 +1 +1 +1 -1 +1 +1 +1 +1 +1
-1 -1 -1 +1 +1 +1 -1 -1 -1 +1
53

Hint

Constraints: For all testdata, 3n8003 \le n \le 800 and 3m8003 \le m \le 800. The absolute value of each gain or cost is at most 100000100000.

Translated by ChatGPT 5