Under construction

Still being built. Things may change

Pixels

Time limit2sMemory limit1024 MB

Summary
Color each pixel of an N by N grid black or white to maximize the color bonuses minus the costs of adjacent pixels with different colors.
Level

Medium7 of 10

Topics
Graph
Solved
No attempts yet

Problem

You are given an NtimesNN \\times N matrix of pixels. Color each pixel black or white so that the end result is as pleasant as possible. You are given three kinds of information. For each pixel (i,j)(i, j), AijA_{ij} is the bonus you get if you color it white. BijB_{ij} is the bonus you get if you color it black. For each pair of adjacent pixels (sharing an edge), CijkC_{ijk} is the cost you pay if the two pixels have different colors.

The cost is given for each pixel and each of its four directions. For pixel (i,j)(i, j), Cij0C_{ij0} is the cost when that pixel and (i−1,j)(i - 1, j) differ, Cij1C_{ij1} is the cost for (i,j+1)(i, j + 1), Cij2C_{ij2} is the cost for (i+1,j)(i + 1, j), and Cij3C_{ij3} is the cost for (i,j−1)(i, j - 1). If a neighbor is outside the matrix, its cost is still given as 0. Cij0C_{ij0} and C(i−1)j2C_{(i-1)j2} are always equal, and the same symmetry holds for the other directions.

Maximize the sum of AijA_{ij} over white pixels plus the sum of BijB_{ij} over black pixels, minus the costs of adjacent pairs with different colors. Each such pair is counted once.

Input

The first line contains NN. The next NN lines each contain NN values, where the jj-th value on line ii is AijA_{ij}. In the same format, the next NN lines contain BijB_{ij}. Finally, NtimesNN \\times N lines follow, each with four values Cij0C_{ij0}, Cij1C_{ij1}, Cij2C_{ij2}, Cij3C_{ij3}. The ((i−1)timesN+j)((i-1) \\times N + j)-th of these lines belongs to pixel (i,j)(i, j).

Output

Print one line containing the maximum possible pleasantness.

Constraints

1leNle1001 \\le N \\le 100

1leAij,Bij,Cijkle1001 \\le A_{ij}, B_{ij}, C_{ijk} \\le 100

Hint

The only possible coloring for the optimal pleasantness is:

Black White
Black Black

The cost of coloring (2,1)(2, 1) and (2,2)(2, 2) differently is very high, so they should share a color. Black is the better choice for them. For (1,1)(1, 1) and (1,2)(1, 2), the better option is clear.

Examples1

  1. Example 1

    Input
    2
    1 10
    2 2
    10 1
    3 3
    0 1 1 0
    0 0 1 1
    1 53 0 0
    1 0 0 53
    
    Expected output
    24