let rec select acc trace = function
  | [] -> acc
  | x :: xs -> select ((trace, x, xs) :: acc) (x :: trace) xs
let select xs = select [] [] xs

(* 与えられたリストからn要素を選ぶ順列 *)
let rec perm : int -> 'a list -> 'a list list = fun n xs ->
  match n, xs with
  | 0, _ -> [[]]
  | _, [] -> []
  | n, xs ->
      List.concat @@
        List.map (fun (xs, x, ys) ->
          List.map (fun xs -> x :: xs) @@
            perm (n - 1) @@ List.rev_append xs ys) @@ select xs;;

let () = Scanf.scanf "%d %d\n" @@ fun n c ->
  let dss =
    Array.init c @@ fun _ ->
      Array.init c @@ fun _ ->
        Scanf.scanf "%d " @@ fun d -> d in
  let css =
    Array.init n @@ fun _ ->
      Array.init n @@ fun _ ->
        Scanf.scanf "%d " @@ fun c -> c in
  let colours = Array.make_matrix 3 c 0 in
  Array.iteri (fun i ->
    Array.iteri (fun j c ->
      colours.((i + j + 2) mod 3).(c - 1) <- colours.((i + j + 2) mod 3).(c - 1) + 1)) css;
  Array.init c (fun c -> c)
  |> Array.to_list
  |> perm 3
  |> List.map (List.mapi (fun m y ->
      Array.mapi (fun x n -> n * dss.(x).(y)) colours.(m)
      |> Array.fold_left ( + ) 0))
  |> List.map (List.fold_left ( + ) 0)
  |> List.fold_left min max_int
  |> Printf.printf "%d\n"
