Under construction

Still being built. Things may change

Tube Master II

Time limit2sMemory limit512 MB

Summary
Pick tube segments so each crossing uses either nothing or one horizontal and one vertical tube, meeting every cell's required count at minimum total cost.
Level

Hard8 of 10

Topics
Dynamic programming, Bit manipulation, Matrix
Solved
No attempts yet

Problem

Yuuka is playing "Tube Master". The game field is divided into n×mn \times m cells and (n+1)×(m+1)(n + 1) \times (m + 1) crossings. The crossings are connected by (n+1)×m(n + 1) \times m horizontal tubes and n×(m+1)n \times (m + 1) vertical tubes. The cells are labeled (i,j)(i, j) for 1≤i≤n1 \leq i \leq n, 1≤j≤m1 \leq j \leq m, and the crossings are labeled (i,j)(i, j) for 1≤i≤(n+1)1 \leq i \leq (n+1), 1≤j≤(m+1)1 \leq j \leq (m+1). Each cell (i,j)(i, j) contains an integer count_i,j\mathit{count}\_{i, j}.

Yuuka decides to use some of the tubes, subject to these restrictions:

  1. Either 0 or 2 tubes connected to each crossing are used.
  2. No two consecutive horizontal tubes are used at the same time, and no two consecutive vertical tubes are used at the same time. Two tubes are consecutive if and only if they share a crossing.
  3. Exactly count_i,j\mathit{count}\_{i, j} of the tubes surrounding cell (i,j)(i, j) are used.

Using the tube connecting crossings (i,j)(i, j) and (i,j+1)(i, j + 1) costs a_i,ja\_{i, j}. Using the tube connecting crossings (i,j)(i, j) and (i+1,j)(i + 1, j) costs b_i,jb\_{i, j}. Find a configuration that satisfies the restrictions with the minimum total cost.

Input

The input contains zero or more test cases and ends at end-of-file. For each test case:

The first line contains two integers nn and mm (1≤n,m≤1001 \leq n, m \leq 100).

The ii-th of the following nn lines contains mm integers count_i,1,count_i,2,…,count_i,m\mathit{count}\_{i, 1}, \mathit{count}\_{i, 2}, \dots, \mathit{count}\_{i, m} (0≤count_i,j≤40 \leq \mathit{count}\_{i, j} \leq 4).

The ii-th of the next (n+1)(n + 1) lines contains mm integers a_i,1,a_i,2,…,a_i,ma\_{i, 1}, a\_{i, 2}, \dots, a\_{i, m}.

The ii-th of the last nn lines contains (m+1)(m + 1) integers b_i,1,b_i,2,…,b_i,m+1b\_{i, 1}, b\_{i, 2}, \dots, b\_{i, m + 1}.

The constraints are 1≤a_i,j,b_i,j≤1091 \leq a\_{i, j}, b\_{i, j} \leq 10^9. The sum of n⋅mn \cdot m over all test cases does not exceed 10410^4.

Output

For each test case, output the minimum cost of a valid configuration. If no valid configuration exists, output "-1" instead.

Examples1

  1. Example 1

    Input
    1 3
    4 2 4
    1 1 1
    1 1 1
    1 1 1 1
    1 2
    3 3
    1 1
    1 1
    1 1 1
    3 3
    2 3 2
    3 0 3
    2 3 2
    1 2 3
    4 5 6
    7 8 9
    11 12 13
    1 2 3 4
    5 6 7 8
    9 10 11 12
    
    Expected output
    8
    -1
    79