100 #ABC099D. [ABC099D] Good Grid

[ABC099D] Good Grid

Score : 400400 points

Problem Statement

There is a grid with NN rows and NN columns of squares. Let (i,j)(i,j) be the square at the ii-th row from the top and the jj-th column from the left.

These squares have to be painted in one of the CC colors from Color 11 to Color CC. Initially, (i,j)(i,j) is painted in Color ci,jc_{i,j}.

We say the grid is a good grid when the following condition is met for all i,j,x,yi,j,x,y satisfying 1i,j,x,yN1 \leq i,j,x,y \leq N:

  • If (i+j)%3=(x+y)%3(i+j) \% 3=(x+y) \% 3, the color of (i,j)(i,j) and the color of (x,y)(x,y) are the same.
  • If (i+j)%3(x+y)%3(i+j) \% 3 \neq (x+y) \% 3, the color of (i,j)(i,j) and the color of (x,y)(x,y) are different.

Here, X%YX \% Y represents XX modulo YY.

We will repaint zero or more squares so that the grid will be a good grid.

For a square, the wrongness when the color of the square is XX before repainting and YY after repainting, is DX,YD_{X,Y}.

Find the minimum possible sum of the wrongness of all the squares.

Constraints

  • 1N5001 \leq N \leq 500
  • 3C303 \leq C \leq 30
  • $1 \leq D_{i,j} \leq 1000 (i \neq j),D_{i,j}=0 (i=j)$
  • 1ci,jC1 \leq c_{i,j} \leq C
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN CC

D1,1D_{1,1} ...... D1,CD_{1,C}

::

DC,1D_{C,1} ...... DC,CD_{C,C}

c1,1c_{1,1} ...... c1,Nc_{1,N}

::

cN,1c_{N,1} ...... cN,Nc_{N,N}

Output

If the minimum possible sum of the wrongness of all the squares is xx, print xx.

2 3
0 1 1
1 0 1
1 4 0
1 2
3 3
3
  • Repaint (1,1)(1,1) to Color 22. The wrongness of (1,1)(1,1) becomes D1,2=1D_{1,2}=1.
  • Repaint (1,2)(1,2) to Color 33. The wrongness of (1,2)(1,2) becomes D2,3=1D_{2,3}=1.
  • Repaint (2,2)(2,2) to Color 11. The wrongness of (2,2)(2,2) becomes D3,1=1D_{3,1}=1.

In this case, the sum of the wrongness of all the squares is 33.

Note that Di,jDj,iD_{i,j} \neq D_{j,i} is possible.

4 3
0 12 71
81 0 53
14 92 0
1 1 2 1
2 1 1 2
2 2 1 3
1 1 2 2
428