Problem:
Score : 400 points

Problem Statement

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

These squares have to be painted in one of the C colors from Color 1 to Color C. Initially, (i,j) is painted in Color c_{i,j}.

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

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

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

Here, X \% Y represents X modulo Y.

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 X before repainting and Y after repainting, is D_{X,Y}.

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

Constraints

1 \leq N \leq 500

3 \leq C \leq 30

1 \leq D_{i,j} \leq 1000 (i \neq j),D_{i,j}=0 (i=j)

1 \leq c_{i,j} \leq C

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N C
D_{1,1} ... D_{1,C}
:
D_{C,1} ... D_{C,C}
c_{1,1} ... c_{1,N}
:
c_{N,1} ... c_{N,N}

Output

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

Sample Input 1

2 3
0 1 1
1 0 1
1 4 0
1 2
3 3

Sample Output 1

3

Repaint (1,1) to Color 2. The wrongness of (1,1) becomes D_{1,2}=1.

Repaint (1,2) to Color 3. The wrongness of (1,2) becomes D_{2,3}=1.

Repaint (2,2) to Color 1. The wrongness of (2,2) becomes D_{3,1}=1.

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

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

Sample Input 2

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

Sample Output 2

428

Solution in Rust (1.15.1) (judge verdict: Accepted)

#![allow(unused_imports)]
#![allow(unused_variables)]
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(deprecated)]

use std::cell::{Cell, Ref, RefCell, RefMut};
use std::cmp::{max, min, Ordering};
use std::collections::*;
use std::fmt::{Debug, Formatter, Write as FmtWrite};
use std::io::{stderr, stdin, BufRead, Write};
use std::mem::{replace, swap};
use std::ops::*;
use std::rc::Rc;
use std::usize;

const MOD_10_9_7: u64 = 1_000_000_007;
const INF: i64 = 1_000_000_000_000;
const MIN_INF: i64 = -1_000_000_000_000;

/// FYI: https://github.com/vain0x/scan-bench
#[allow(unused_macros)]
macro_rules! read {
    ([$t:ty] ; $n:expr) =>
        ((0..$n).map(|_| read!([$t])).collect::<Vec<_>>());
    ($($t:ty),+ ; $n:expr) =>
        ((0..$n).map(|_| read!($($t),+)).collect::<Vec<_>>());
    ([$t:ty]) =>
        (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::<Vec<$t>>());
    ($t:ty) =>
        (rl().parse::<$t>().unwrap());
    ($($t:ty),*) => {{
        let buf = rl();
        let mut w = buf.split_whitespace();
        ($(w.next().unwrap().parse::<$t>().unwrap()),*)
    }};
}

fn rl() -> String {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    buf.trim_right().to_owned()
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

fn main() {
    let (n, c) = read!(usize, usize);
    let mut d: Vec<Vec<usize>> = vec![];
    for i in 0..c {
        let t: Vec<usize> = read![[usize]];
        d.push(t);
    }
    let mut color = vec![];
    for i in 0..n {
        let t: Vec<usize> = read![[usize]];
        color.push(t);
    }

    // 行と列の和をkとする。kを3で割った余りでグループ分けし、グループ0, 1, 2とする。
    // 各グループをどの色で塗ることにすれば一番違和感が小さくなるのかを考える。

    // グループ0の塗り方c0, 以下順にc1, c2とする
    let mut min_diff = INF as usize;

    // g0, g1, g2 それぞれで元の色iが何個あるのかをあらかじめ数えておくことで計算量減らせないかな？
    let mut g0_map = HashMap::new();
    let mut g1_map = HashMap::new();
    let mut g2_map = HashMap::new();
    for i in 0..n {
        for k in 0..n {
            let ii = i + 1;
            let kk = k + 1;
            match (ii + kk) % 3 {
                0 => {
                    *g0_map.entry(color[i][k] - 1).or_insert(0) += 1;
                }
                1 => {
                    *g1_map.entry(color[i][k] - 1).or_insert(0) += 1;
                }
                2 => {
                    *g2_map.entry(color[i][k] - 1).or_insert(0) += 1;
                }
                _ => (),
            };
        }
    }

    for c0 in 0..c {
        for c1 in 0..c {
            for c2 in 0..c {
                if c0 == c1 || c1 == c2 || c2 == c0 {
                    continue;
                }
                let mut g0_diff = 0;
                let mut g1_diff = 0;
                let mut g2_diff = 0;
                for (&cc, &num) in &g0_map {
                    g0_diff += d[cc][c0] * num;
                }
                for (&cc, &num) in &g1_map {
                    g1_diff += d[cc][c1] * num;
                }
                for (&cc, &num) in &g2_map {
                    g2_diff += d[cc][c2] * num;
                }
                min_diff = min(min_diff, g0_diff + g1_diff + g2_diff);
            }
        }
    }

    println!("{}", min_diff);
}