#P6545. [CEOI 2014] The Wall

[CEOI 2014] The Wall

Description

Rectos Island is often hit by floods and attacked by pirates, so the King of Rectos wants to build a wall to protect all villages on the island.

Rectos is a rectangular island, so the wall designer views the island as a square grid. Each village is located in one cell of the grid, and the capital village is located at the northwest corner of the whole island, i.e., the top-left cell.

It must be guaranteed that from the outside (i.e., outside the entire grid), it is impossible to reach any village without crossing the wall.

The designer plans to build the wall only along grid lines. More specifically, he places the first segment of the wall on one of the two grid lines extending from the top-left corner, and each next segment is always connected end-to-end with the previous segment. This process is repeated until it returns to the top-left corner again. This may cause more than one segment of wall to be placed on the same grid edge. In summary, the wall is built as a continuous closed curve along the grid lines.

Survey data show that building one segment of wall on each grid edge costs a certain amount. The total cost is the sum of the costs of all wall segments. If tt wall segments are built on a certain grid edge, then its cost is counted tt times.

The King wants to build the wall with as little money as possible. Please help the King: given the positions of the villages and the building cost on each grid edge, compute the minimum total cost needed to build the wall.

Input Format

The first line contains two positive integers n,mn, m, representing the number of rows and columns of the grid.
Then follow nn lines, each containing mm numbers, each being 00 or 11. If it is 00, the cell has no village; if it is 11, the cell has a village. It is guaranteed that the first number in the first row is 11.
Then follow nn lines, each containing m+1m + 1 non-negative integers, describing in order the building cost on each vertical grid edge.
Then follow n+1n + 1 lines, each containing mm non-negative integers, describing in order the building cost on each horizontal grid edge.

Output Format

Output one line with one number, representing the minimum cost to build the wall.

3 3
1 0 0
1 0 0
0 0 1
1 4 9 4
1 6 6 6
1 2 2 9
1 1 1
4 4 4
2 4 2
6 6 6
38
3 3
1 0 1
0 0 0
0 1 0
2 1 1 3
5 6 1 1
2 1 1 3
2 1 1
3 4 1
4 1 1
5 1 2
22

Hint

[Sample #1 Explanation]

[Sample #2 Explanation]

[Constraints and Notes]

For all testdata, 1n,m4001 \le n, m \le 400. For every building cost vv, 1v1091 \le v \le {10}^9.

Subtask ID Score Special Constraints
11 3030 n,m40n, m \le 40 and the number of villages does not exceed 1010
22 n,m40n, m \le 40
33 4040 No special constraints

Translated by ChatGPT 5