Maximum Sum Path

Time limit: 1s Memory limit: 256MB Input: Output:

Task

Given a grid of integers AA consisting of NN rows and MM columns, where each of its cells has a color and a number written on it.

Find the maximum sum of numbers on the cells of a path that goes only right and down, such that its starting and ending cells have the same color.

Input data

The input file consists of:

  • a line containing integers NN, MM.
  • NN lines, the ii-th of which consisting of the MM integers Ai,0,,Ai,M1A_{i,0}, \, \ldots, \, A_{i,M-1}, where Ai,jA_{i,j} is the integer in the cell (i,j)(i, j).
  • NN lines, the ii-th of which consisting of the MM integers Ci,0,,Ci,M1C_{i,0}, \, \ldots, \, C_{i,M-1}, where Ci,jC_{i,j} is the color of the cell (i,j)(i, j).

Output data

Output a single line containing a single integer -- the answer to the problem.

Constraints and clarifications

  • 1N5001 \le N \le 500.
  • 1M5001 \le M \le 500.
  • 109Ai,j109-10^9 \le A_{i,j} \le 10^9 for each i=0N1i=0\ldots N-1 and j=0M1j=0\ldots M-1.
  • 1Ci,j5001 \le C_{i,j} \le 500 for each i=0N1i=0\ldots N-1 and j=0M1j=0\ldots M-1.
# Score Constraints
1 0 Examples
2 4 N2N \le 2 and M2M \le 2
3 7 N30N \le 30 and M30M \le 30
4 18 N100N \le 100 and M100M \le 100
5 5 Ci,j1C_{i,j} \le 1
6 12 Ci,j2C_{i,j} \le 2
7 54 No additional restrictions

Example 1

stdin

3 3
1 1 2
0 -1 -4
1 5 1
3 2 3
4 5 6
2 3 1

stdout

7

Explanation

In the first example, the maximum sum path goes through the cells (0,0)(0, 0), (1,0)(1, 0), (2,0)(2, 0), (2,1)(2, 1).

Notice that it's possible to achieve a greater sum by continuing to the cell (2,2)(2, 2),
but that path shouldn't be considered because its starting cell (0,0)(0, 0) has a different color form its ending cell (2,2)(2, 2).

Example 2

stdin

2 2
0 -1
1 1
1 1
1 1

stdout

2

Explanation

In the second example, the maximum sum path goes through the cells (1,0)(1, 0) and (1,1)(1, 1).

Log in or sign up to be able to send submissions!