AtCoder Beginner Contest 099 - Good Grid

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-----
2 3
0 1 1
1 0 1
1 4 0
1 2
3 3

-----Sample Output-----
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.

Difficulty: MEDIUM

Starter code:

Solutions:
(N, C) = map(int, input().split())
D = [[int(i) for i in input().split()] for j in range(C)]
co = [[int(i) for i in input().split()] for j in range(N)]
A = [[0] * C for i in range(3)]
for i in range(N):
	for j in range(N):
		t = (i + j) % 3
		for s in range(C):
			A[t][s] += D[co[j][i] - 1][s]
ans = 10 ** 13
for x in range(C):
	for y in range(C):
		if x == y:
			continue
		for z in range(C):
			if x == z or y == z:
				continue
			ans = min(ans, A[0][x] + A[1][y] + A[2][z])
print(ans)


from collections import Counter
from itertools import permutations
(n, c) = list(map(int, input().split()))
D = []
for i in range(c):
	D.append(list(map(int, input().split())))
co = [Counter() for i in range(3)]
for i in range(n):
	C = list(map(int, input().split()))
	for j in range(n):
		co[(i + j) % 3][C[j] - 1] += 1
ans = 10 ** 15
perm = permutations([i for i in range(c)], 3)
for t in perm:
	temp = 0
	for i in range(3):
		color = t[i]
		for (num, cnt) in list(co[i].items()):
			temp += D[num][color] * cnt
	ans = min(temp, ans)
print(ans)


(n, c) = map(int, input().split())
dll = []
for _ in range(c):
	dl = list(map(int, input().split()))
	dll.append(dl)
cll = []
for _ in range(n):
	cl = list(map(int, input().split()))
	cll.append(cl)
d_sum = [[0 for i in range(c)] for j in range(3)]
for i in range(c):
	for j in range(n):
		for k in range(n):
			d_sum[(j + k) % 3][i] += dll[cll[j][k] - 1][i]
import itertools
c_set = [i for i in range(c)]
c_list = list(itertools.permutations(c_set, 3))
ans = float('inf')
for (c1, c2, c3) in c_list:
	tmp = d_sum[0][c1] + d_sum[1][c2] + d_sum[2][c3]
	if ans > tmp:
		ans = tmp
print(ans)


from itertools import permutations
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
rem = [[] for _ in range(3)]
for i in range(N):
	for j in range(N):
		rem[(i + j + 2) % 3].append(c[i][j])
cost = [[] for _ in range(3)]
for i in range(3):
	for s in range(C):
		tmp = 0
		for t in rem[i]:
			tmp += D[t - 1][s]
		cost[i].append((tmp, s + 1))
for i in cost:
	i.sort()
	i = i[:3]
ans = 10000000000.0
for i in cost[0]:
	for j in cost[1]:
		for h in cost[2]:
			if i[1] != j[1] and j[1] != h[1] and (h[1] != i[1]):
				ans = min(ans, i[0] + j[0] + h[0])
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
G = [list(map(int, input().split())) for _ in range(N)]
cost = [[0] * C for _ in range(3)]
for i in range(C):
	for a in range(N):
		for b in range(N):
			cost[(a + b) % 3][i] += D[G[a][b] - 1][i]
ans = 10 ** 10
for i in range(C):
	for j in range(C):
		for k in range(C):
			if i == j or j == k or k == i:
				pass
			else:
				ans = min(ans, cost[0][i] + cost[1][j] + cost[2][k])
print(ans)


import sys
from itertools import permutations
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007

def main():
	(N, C) = list(map(int, readline().split()))
	D = [0] * C
	for i in range(C):
		D[i] = list(map(int, readline().split()))
	G = [0] * N
	for i in range(N):
		G[i] = [int(s) - 1 for s in readline().split()]
	cost = [[0] * C for _ in range(3)]
	for x in range(N):
		for y in range(N):
			color = G[x][y]
			cost_current = cost[(x + y) % 3]
			for i in range(C):
				cost_current[i] += D[color][i]
	ans = INF
	for (c1, c2, c3) in permutations(list(range(C)), 3):
		if ans > cost[0][c1] + cost[1][c2] + cost[2][c3]:
			ans = cost[0][c1] + cost[1][c2] + cost[2][c3]
	print(ans)
	return

def __starting_point():
	main()
__starting_point()


(n, c) = map(int, input().split())
D = [[0]]
for i in range(c):
	D.append([0] + list(map(int, input().split())))
color_num = [[0] * (c + 1) for i in range(3)]
for i in range(n):
	tmp = list(map(int, input().split()))
	for j in range(n):
		color_num[(i + j + 2) % 3][tmp[j]] += 1
ans = []
for i in range(1, c + 1):
	for j in range(1, c + 1):
		for k in range(1, c + 1):
			if i != j and j != k and (k != i):
				tmp = 0
				for m in range(1, c + 1):
					tmp += color_num[0][m] * D[m][i] + color_num[1][m] * D[m][j] + color_num[2][m] * D[m][k]
				ans.append(tmp)
print(min(ans))


import itertools
(N, C) = map(int, input().split())
D = [[int(x) for x in input().split()] for _ in range(C)]
CC = [[int(x) - 1 for x in input().split()] for _ in range(N)]
cost = [[0 for _ in range(C)] for _ in range(3)]
for c in range(C):
	for i in range(N):
		for j in range(N):
			cost[(i + j) % 3][c] += D[CC[i][j]][c]
ans = float('inf')
for c in itertools.permutations(range(C), 3):
	tmp = 0
	for j in range(3):
		tmp += cost[j][c[j]]
	ans = min(ans, tmp)
print(ans)


import itertools
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
G = [list(map(int, input().split())) for _ in range(N)]
count_color = [[0 for _ in range(C + 1)] for _ in range(3)]
for y in range(N):
	for x in range(N):
		count_color[(x + y) % 3][G[y][x]] += 1
ans = 10 ** 12
for colors in itertools.permutations(range(1, C + 1), 3):
	iwakan = 0
	for mod in range(3):
		for c in range(1, C + 1):
			iwakan += D[c - 1][colors[mod] - 1] * count_color[mod][c]
	if iwakan < ans:
		ans = iwakan
print(ans)


from collections import defaultdict
import itertools
(n, c) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(c)]
diago = [defaultdict(int) for _ in range(3)]
for i in range(n):
	for (j, color) in enumerate(map(int, input().split())):
		color -= 1
		if (i + j) % 3 == 0:
			diago[0][color] += 1
		elif (i + j) % 3 == 1:
			diago[1][color] += 1
		else:
			diago[2][color] += 1
costs = [[0] * c for _ in range(3)]
for i in range(3):
	for j in range(c):
		for (k, v) in diago[i].items():
			costs[i][j] += D[k][j] * v
INF = 10 ** 18
ans = INF
for trio in itertools.combinations(range(c), 3):
	for color in itertools.permutations(trio, 3):
		cost = sum((costs[i][j] for (i, j) in enumerate(color)))
		if cost < ans:
			ans = cost
print(ans)


from itertools import permutations
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
cost = [[0] * 3 for _ in range(C)]
for i in range(N):
	for j in range(N):
		for k in range(C):
			cost[k][(i + j) % 3] += D[c[i][j] - 1][k]
ans = min((sum((cost[c][i] for (i, c) in enumerate(colors))) for colors in permutations(range(C), 3)))
print(ans)


(n, c) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(c)]
Grid = [list(map(int, input().split())) for _ in range(n)]
Counter = [[0] * c for _ in range(3)]
for i in range(n):
	for j in range(n):
		Counter[(i + j) % 3][Grid[i][j] - 1] += 1
Cost = [[0] * c for _ in range(3)]
for i in range(3):
	for j in range(c):
		for (k, cnt) in enumerate(Counter[i]):
			Cost[i][j] += D[k][j] * cnt
ans = float('inf')
for i in range(c):
	for j in range(c):
		for k in range(c):
			if i == j or j == k or k == i:
				continue
			ans = min(ans, Cost[0][i] + Cost[1][j] + Cost[2][k])
print(ans)


from collections import defaultdict
from itertools import permutations
(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
cmat = [list(map(int, input().split())) for _ in range(n)]
dcnt = [defaultdict(int) for _ in range(3)]
for (i, ci) in enumerate(cmat, 1):
	for (j, cij) in enumerate(ci, 1):
		mod = (i + j) % 3
		dcnt[mod][cij - 1] += 1
ans = 1000 * n ** 2
for color in permutations(range(c), 3):
	tmp = 0
	for (i, cnt) in enumerate(dcnt):
		tmp += sum((d[k][color[i]] * cnt[k] for k in cnt))
	ans = min(ans, tmp)
print(ans)


from itertools import product, permutations
(N, C) = map(int, input().split())
D = [tuple(map(int, input().split())) for _ in range(C)]
grid = [tuple(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]
cnt = [[0] * C for _ in range(3)]
for (x, y) in product(range(N), range(N)):
	cnt[(x + y) % 3][grid[x][y]] += 1

def it():
	for p in permutations(range(C), r=3):
		yield sum((n * D[i][j] for (s, j) in zip(range(3), p) for (i, n) in enumerate(cnt[s])))
print(min(it()))


from itertools import permutations
(n, C) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(n)]
a = [[0] * C for _ in range(3)]
for i in range(n):
	for j in range(n):
		a[(i + j) % 3][c[i][j] - 1] += 1
ans = 10 ** 9
for v in permutations(range(C), 3):
	tmp = 0
	for i in range(3):
		for j in range(C):
			tmp += a[i][j] * d[j][v[i]]
	ans = min(ans, tmp)
print(ans)


from itertools import permutations
(N, C) = list(map(int, input().split()))
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
cnt = [[0] * (C + 1) for _ in range(3)]
disc = [[0] * (C + 1) for _ in range(3)]
for i in range(N):
	for j in range(N):
		cnt[(i + j) % 3][c[i][j]] += 1
for i in range(3):
	for j in range(C):
		for k in range(C):
			disc[i][j] += D[k][j] * cnt[i][k + 1]
ans = 10 ** 10
for (i, j, k) in permutations(range(C), 3):
	ans = min(ans, disc[0][i] + disc[1][j] + disc[2][k])
print(ans)


from collections import defaultdict
from itertools import permutations
(n, c) = list(map(int, input().split()))
d = [list(map(int, input().split())) for _ in range(c)]
cmat = [list(map(int, input().split())) for _ in range(n)]
dcnt = [defaultdict(int) for _ in range(3)]
for (i, ci) in enumerate(cmat, 1):
	for (j, cij) in enumerate(ci, 1):
		mod = (i + j) % 3
		dcnt[mod][cij - 1] += 1
ans = 10 ** 9
for color in permutations(list(range(c)), 3):
	if len(set(color)) == 3:
		tmp = 0
		for (i, cnt) in enumerate(dcnt):
			tmp += sum((d[k][color[i]] * cnt[k] for k in cnt))
		ans = min(ans, tmp)
print(ans)


from collections import Counter
from itertools import permutations

def main():
	(N, C) = map(int, input().split())
	D = [[int(x) for x in input().split()] for _ in range(C)]
	cnt = [Counter() for _ in range(3)]
	for i in range(N):
		c = [int(x) - 1 for x in input().split()]
		for j in range(3):
			cnt[j].update(c[(3 - (i + 2) + j) % 3::3])
	ans = 1000 * 500 * 500 + 5
	for p in permutations(range(C), 3):
		s = 0
		for j in range(3):
			s += sum((D[k][p[j]] * v for (k, v) in cnt[j].items()))
		ans = min(ans, s)
	print(ans)
main()


(n, c) = list(map(int, input().split()))
iwaka = [list(map(int, input().split())) for i in range(c)]
masu = [list(map(int, input().split())) for i in range(n)]
amari = [{} for i in range(3)]
for i in range(n):
	for j in range(n):
		amari[(i + j) % 3][masu[i][j]] = amari[(i + j) % 3].get(masu[i][j], 0) + 1
kouho = []
for i in range(c):
	for j in range(c):
		for k in range(c):
			if i != j and j != k and (k != i):
				kouho.append((i + 1, j + 1, k + 1))
ans = 10 ** 9
for p in kouho:
	cou = 0
	for i in range(3):
		for (k, v) in list(amari[i].items()):
			cou += iwaka[k - 1][p[i] - 1] * v
	ans = min(ans, cou)
print(ans)


(N, C) = map(int, input().split())
s = [list(map(int, input().split())) for i in range(C)]
t = [[0] * C for i in range(3)]
(ll, kk) = ([], [[0] * C for i in range(3)])
for k in range(N):
	for (i, j) in enumerate(list(map(int, input().split()))):
		t[(i + k) % 3][j - 1] += 1
for j in range(3):
	for i in range(C):
		for k in range(C):
			kk[j][k] += s[i][k] * t[j][i]
from itertools import permutations
ans = 10 ** 9
for (i, j, k) in permutations(range(C), 3):
	p = kk[0][i] + kk[1][j] + kk[2][k]
	ans = min(ans, kk[0][i] + kk[1][j] + kk[2][k])
print(ans)


(N, C) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(C)]
g0 = [0] * C
g1 = [0] * C
g2 = [0] * C
for i in range(N):
	col = list(map(int, input().split()))
	for j in range(N):
		col[j] -= 1
		if (i + j) % 3 == 0:
			g0[col[j]] += 1
		elif (i + j) % 3 == 1:
			g1[col[j]] += 1
		else:
			g2[col[j]] += 1
ans = float('inf')
for i in range(C):
	for j in range(C):
		for k in range(C):
			if i == j or j == k or i == k:
				continue
			s = 0
			for l in range(C):
				s += d[l][i] * g0[l] + d[l][j] * g1[l] + d[l][k] * g2[l]
			ans = min(ans, s)
print(ans)


from itertools import permutations as per
(n, c) = map(int, input().split())
d = [tuple(map(int, input().split())) for i in range(c)]
g = [[0] * c, [0] * c, [0] * c]
for i in range(1, n + 1):
	ci = tuple(map(int, input().split()))
	for j in range(1, n + 1):
		g[(i + j) % 3][int(ci[j - 1]) - 1] += 1
m = 10 ** 10
for i in per(range(c), 3):
	e = 0
	for j in range(3):
		for o in range(c):
			e += g[j][o] * d[o][i[j] - 1]
	m = min(m, e)
print(m)


from itertools import permutations as perm
(N, C) = map(int, input().split())
colors = []
for i in range(C):
	colors.append(list(map(int, input().split())))
grids = {0: {}, 1: {}, 2: {}}
for i in range(1, N + 1):
	A = list(map(int, input().split()))
	for j in range(N):
		if A[j] not in grids[(i + j + 1) % 3]:
			grids[(i + j + 1) % 3][A[j]] = 1
		else:
			grids[(i + j + 1) % 3][A[j]] += 1
mn = 10 ** 9
for color in perm([i for i in range(1, C + 1)], 3):
	tmp = 0
	for i in range(3):
		for (k, v) in grids[i].items():
			tmp += colors[k - 1][color[i] - 1] * v
	mn = min(mn, tmp)
print(mn)


from itertools import product, permutations
(n, c) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(c)]
C = [list(map(int, input().split())) for _ in range(n)]
X = [[0] * c for i in range(3)]
for i in range(n):
	for j in range(n):
		X[(i + j + 2) % 3][C[i][j] - 1] += 1
cost = [[0] * c for i in range(3)]
for i in range(c):
	for j in range(c):
		cost[0][j] += X[0][i] * D[i][j]
		cost[1][j] += X[1][i] * D[i][j]
		cost[2][j] += X[2][i] * D[i][j]
ans = []
for (s, t, u) in permutations(range(c), r=3):
	ans.append(cost[0][s] + cost[1][t] + cost[2][u])
print(min(ans))


from collections import Counter
from itertools import permutations
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
c = [list(map(lambda s: int(s) - 1, input().split())) for i in range(N)]
d = [Counter(sum([c[j][(i - j) % 3::3] for j in range(N)], [])) for i in range(3)]
ans = 1000000007
for t in permutations(range(C), 3):
	dis = 0
	for i in range(3):
		for (k, v) in d[i].items():
			dis += D[k][t[i]] * v
	ans = min(dis, ans)
print(ans)


from itertools import permutations
(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
cmat = [list(map(int, input().split())) for _ in range(n)]
dcnt = [[0] * c for _ in range(3)]
for (i, ci) in enumerate(cmat):
	for (j, cij) in enumerate(ci):
		mod = (i + j) % 3
		dcnt[mod][cij - 1] += 1
ans = 10 ** 9
for color in permutations(range(c), 3):
	tmp = 0
	for (tgt, cnt) in zip(color, dcnt):
		tmp += sum((d[i][tgt] * cnt[i] for i in range(c)))
	ans = min(ans, tmp)
print(ans)


import sys
import collections
import itertools
input = sys.stdin.readline

def main():
	(N, C) = [int(x) for x in input().split()]
	D = [[int(x) for x in input().split()] for _ in range(C)]
	c = [[int(x) for x in input().split()] for _ in range(N)]
	A = [[] for j in range(3)]
	for j in range(N):
		for i in range(N):
			A[(i + j) % 3].append(c[j][i])
	one = collections.Counter(A[0])
	two = collections.Counter(A[1])
	three = collections.Counter(A[2])
	ans = float('inf')
	for (x, y, z) in itertools.permutations(list(range(C)), 3):
		tmp = 0
		for k in list(one.keys()):
			tmp += D[k - 1][x] * one[k]
		for k in list(two.keys()):
			tmp += D[k - 1][y] * two[k]
		for k in list(three.keys()):
			tmp += D[k - 1][z] * three[k]
		ans = min(ans, tmp)
	print(ans)

def __starting_point():
	main()
__starting_point()


(n, c) = list(map(int, input().split()))
change_cost = [list(map(int, input().split())) for _ in range(c)]
init_color = [list(map(int, input().split())) for _ in range(n)]
cost = [[0 for _ in range(c)] for _ in range(3)]
for row in range(n):
	for col in range(n):
		before = init_color[row][col] - 1
		for after in range(c):
			idx = (row + col) % 3
			cost[idx][after] += change_cost[before][after]
ans = 1000 * 500 * 500 * 10
for ci in range(c):
	for cj in range(c):
		for ck in range(c):
			if ci != cj != ck != ci:
				ans = min(ans, cost[0][ci] + cost[1][cj] + cost[2][ck])
print(ans)


from collections import defaultdict
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
cnt = [defaultdict(int) for i in range(3)]
for i in range(N):
	s = list(map(int, input().split()))
	for j in range(N):
		t = (i + j + 2) % 3
		cnt[t][s[j] - 1] += 1
ans = 10 ** 9
for x in range(C):
	for y in range(C):
		for z in range(C):
			if x == y or y == z or z == x:
				continue
			tmp = 0
			for (i, c) in enumerate([x, y, z]):
				for key in cnt[i]:
					tmp += D[key][c] * cnt[i][key]
			ans = min(ans, tmp)
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
cd = [[] for _ in range(3)]
for i in range(N):
	for j in range(N):
		cd[(i + j) % 3].append(c[i][j] - 1)
cost = [[0] * C for _ in range(3)]
for i in range(3):
	for j in range(C):
		for x in cd[i]:
			cost[i][j] += D[x][j]
from itertools import product
import pprint
A = list(product(range(C), repeat=3))
ans = float('inf')
for a in A:
	if a[0] == a[1] or a[1] == a[2] or a[2] == a[0]:
		continue
	cnt = 0
	for i in range(3):
		cnt += cost[i][a[i]]
	ans = min(ans, cnt)
print(ans)


from itertools import permutations
(n, c) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(c)]
C = [list(map(int, input().split())) for _ in range(n)]
colors = [[0] * c for _ in range(3)]
for i in range(n):
	for j in range(n):
		c_ij = C[i][j] - 1
		index = (i + j) % 3
		for col in range(c):
			colors[index][col] += D[c_ij][col]
ans = 1000 * 500 ** 2
for (c0, c1, c2) in permutations(range(c), 3):
	diff = colors[0][c0] + colors[1][c1] + colors[2][c2]
	ans = min(ans, diff)
print(ans)


import itertools
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
delta = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		for to in range(C):
			delta[(i + j) % 3][to] += D[c[i][j] - 1][to]
ans = 1e+100
for (x, y, z) in itertools.permutations(range(C), 3):
	ans = min(ans, delta[0][x] + delta[1][y] + delta[2][z])
print(ans)


import sys
input = sys.stdin.buffer.readline

def main():
	(n, c) = map(int, input().split())
	D = [list(map(int, input().split())) for _ in range(c)]
	C = [list(map(int, input().split())) for _ in range(n)]
	A = [[0] * c for _ in range(3)]
	for i in range(n):
		for j in range(n):
			x = C[i][j] - 1
			r = (i + j) % 3
			for y in range(c):
				A[r][y] += D[x][y]
	ans = float('inf')
	for i in range(c):
		for j in range(c):
			for k in range(c):
				if i == j or j == k or k == i:
					continue
				temp = A[0][i] + A[1][j] + A[2][k]
				ans = min(ans, temp)
	print(ans)
main()


LI = lambda : list(map(int, input().split()))
(N, C) = LI()
D = [LI() for _ in range(C)]
c = [LI() for _ in range(N)]
INF = 10 ** 15

def main():
	w = [[0] * C for i in range(3)]
	for i in range(N):
		for j in range(N):
			x = (i + j) % 3
			for k in range(C):
				w[x][k] += D[c[i][j] - 1][k]
	ans = INF
	for i in range(C):
		for j in range(C):
			if i == j:
				continue
			for k in range(C):
				if i == k or j == k:
					continue
				ans = min(ans, w[0][i] + w[1][j] + w[2][k])
	print(ans)

def __starting_point():
	main()
__starting_point()


import sys
import math
from collections import deque
from itertools import permutations
sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda : sys.stdin.readline().strip()
NI = lambda : int(input())
NMI = lambda : map(int, input().split())
NLI = lambda : list(NMI())
SI = lambda : input()

def main():
	(N, C) = NMI()
	D = [NLI() for _ in range(C)]
	grid = [list(map(lambda x: int(x) - 1, NMI())) for _ in range(N)]
	grid_mod = [{i: 0 for i in range(C)} for _ in range(3)]
	for h in range(N):
		for w in range(N):
			t = (h + w) % 3
			grid_mod[t][grid[h][w]] += 1
	ans = 10 ** 10
	for colors in permutations(range(C), 3):
		diff = 0
		for i in range(3):
			for (c, n) in grid_mod[i].items():
				diff += D[c][colors[i]] * n
		ans = min(ans, diff)
	print(ans)

def __starting_point():
	main()
__starting_point()


from itertools import permutations
(N, C) = map(int, input().split())
d = [[0] * C for i in range(C)]
for i in range(C):
	d[i] = [int(c) for c in input().split()]
grid = [[0] * C for i in range(3)]
for i in range(N):
	inf = [int(c) - 1 for c in input().split()]
	for j in range(N):
		x = (j + i + 2) % 3
		g = inf[j]
		grid[x][g] += 1
record = [[0] * C for i in range(3)]
for i in range(3):
	for j in range(C):
		m = 0
		for h in range(C):
			m += grid[i][h] * d[h][j]
		record[i][j] = m
ans = 10 ** 9
seq = range(C)
for (i, j, h) in permutations(seq, 3):
	m = record[0][i] + record[1][j] + record[2][h]
	if m < ans:
		ans = m
print(ans)


from itertools import permutations
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
a = [[0] * C for _ in range(3)]
for y in range(N):
	for x in range(N):
		t = (x + 1 + (y + 1)) % 3
		a[t][c[y][x] - 1] += 1
result = float('inf')
for b in permutations(range(C), 3):
	t = 0
	for i in range(3):
		for j in range(C):
			t += a[i][j] * D[j][b[i]]
	result = min(result, t)
print(result)


import itertools
(N, C) = map(int, input().split())
D = [[] for _ in range(C)]
c = [[] for _ in range(N)]
for i in range(C):
	D[i] = list(map(int, input().split()))
for i in range(N):
	c[i] = list(map(int, input().split()))
hist = [[0] * C for i in range(3)]
for i in range(N):
	for j in range(N):
		rem = (i + j + 2) % 3
		hist[rem][c[i][j] - 1] += 1
ans = 10 ** 10
for cset in itertools.permutations(range(C), 3):
	temp = 0
	for i in range(3):
		for j in range(C):
			temp += hist[i][j] * D[j][cset[i]]
	ans = min(ans, temp)
print(ans)


from itertools import permutations

def main():
	(N, C) = map(int, input().split())
	D = [list(map(int, input().split())) for _ in range(C)]
	c = [list(map(int, input().split())) for _ in range(N)]
	score = [[0] * 3 for _ in range(C)]
	for i in range(N):
		for j in range(N):
			for k in range(C):
				score[k][(i + j) % 3] += D[c[i][j] - 1][k]
	ans = float('inf')
	for balls in permutations(range(C), 3):
		tmp = 0
		for i in range(3):
			tmp += score[balls[i]][i]
		ans = min(ans, tmp)
	print(ans)
main()


(N, C) = map(int, input().split())
D = [[int(x) for x in input().split()] for y in range(C)]
c = [[int(x) - 1 for x in input().split()] for y in range(N)]
d = [[0 for x in range(C)] for y in range(3)]
for i in range(N):
	for j in range(N):
		d[(i + j) % 3][c[i][j]] += 1
a = 10 ** 9
for c0 in range(C):
	for c1 in range(C):
		for c2 in range(C):
			if c0 != c1 and c1 != c2 and (c0 != c2):
				a = min(a, sum([d[0][c] * D[c][c0] + d[1][c] * D[c][c1] + d[2][c] * D[c][c2] for c in range(C)]))
print(a)


import itertools

def main():
	(N, C) = list(map(int, input().split(' ')))
	D = [list(map(int, input().split(' '))) for _ in range(C)]
	grids = [list([int(c) - 1 for c in input().split(' ')]) for _ in range(N)]
	color_counts = [[0 for _ in range(C)] for _ in range(3)]
	for i in range(N):
		for j in range(N):
			g = (i + 1 + (j + 1)) % 3
			c = grids[i][j]
			color_counts[g][c] += 1
	min_d = 1000 * 500 * 500
	for dest_colors in itertools.permutations(list(range(C)), 3):
		d = 0
		for g in range(3):
			for c in range(C):
				d += color_counts[g][c] * D[c][dest_colors[g]]
		min_d = min([min_d, d])
	print(min_d)

def __starting_point():
	main()
__starting_point()


import itertools as it
(n, c) = map(int, input().split())
dtab = []
dtab.append([0 for _ in range(c + 1)])
for i in range(c):
	dtab.append([0] + list(map(int, input().split())))
ctab = []
ctab.append([0 for _ in range(n + 1)])
for i in range(n):
	ctab.append([0] + list(map(int, input().split())))
ssd = [{}, {}, {}]
for i in range(1, n + 1):
	for j in range(1, n + 1):
		temp = (i + j) % 3
		temp2 = ctab[i][j]
		ssd[temp][temp2] = ssd[temp].get(temp2, 0) + 1
e = [i + 1 for i in range(c)]
cpm = it.permutations(e, 3)
ming = 999999999
for f in cpm:
	fl = list(f)
	cg = 0
	for i in range(3):
		for p in ssd[i].keys():
			cg += dtab[p][fl[i]] * ssd[i][p]
	ming = min(ming, cg)
print(ming)


import sys
import numpy as np
from itertools import permutations
sr = lambda : sys.stdin.readline().rstrip()
ir = lambda : int(sr())
lr = lambda : list(map(int, sr().split()))
(N, C) = lr()
feeling = np.array([lr() for _ in range(C)])
Cij = [lr() for _ in range(N)]
three = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		remain = (i + j) % 3
		num = Cij[i][j] - 1
		three[remain][num] += 1
three = np.array(three)
answer = 10 ** 10
for X in permutations(list(range(C)), 3):
	temp = 0
	for i in range(3):
		x = X[i]
		y = feeling[:, x]
		temp += (three[i] * y).sum()
	if temp < answer:
		answer = temp
print(answer)


(n, c) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(c)]
C = [list(map(int, input().split())) for _ in range(n)]
CC = [[0] * c for _ in range(3)]
for (h, line) in enumerate(C):
	for (w, i) in enumerate(line):
		CC[(h + w) % 3][i - 1] += 1
ans = 10 ** 19
for i in range(c):
	for j in range(c):
		for k in range(c):
			if i != j and j != k and (k != i):
				score = 0
				score += sum((D[itr][i] * val for (itr, val) in enumerate(CC[0])))
				score += sum((D[itr][j] * val for (itr, val) in enumerate(CC[1])))
				score += sum((D[itr][k] * val for (itr, val) in enumerate(CC[2])))
				ans = min(ans, score)
print(ans)


from collections import Counter
(N, K, *DC) = map(int, open(0).read().split())
D = tuple(zip(*[iter(DC[:K * K])] * K))
C = tuple(zip(*[iter(DC[K * K:])] * N))
A = [Counter() for _ in range(3)]
for k in range(K):
	for i in range(N):
		for j in range(N):
			A[(i + j) % 3][k] += D[C[i][j] - 1][k]
ans = float('inf')
for i in range(K):
	for j in range(K):
		for k in range(K):
			if i == j or j == k or k == i:
				continue
			ans = min(ans, A[0][i] + A[1][j] + A[2][k])
print(ans)


import itertools
(N, C) = map(int, input().split())
D = [tuple(map(int, input().split())) for _ in range(C)]
L = [tuple(map(int, input().split())) for _ in range(N)]
lst = [[0] * 3 for _ in range(C)]
for y in range(N):
	for x in range(N):
		for c in range(C):
			lst[c][(x + y) % 3] += D[L[y][x] - 1][c]
ans = float('inf')
for t in itertools.permutations(range(C), 3):
	ans = min(ans, sum((lst[t[i]][i] for i in range(3))))
print(ans)


from collections import Counter
from itertools import permutations
(n, c) = map(int, input().split())
a = []
b = []
for _ in range(c):
	array = list(map(int, input().split()))
	a.append(array)
for _ in range(n):
	array = list(map(int, input().split()))
	b.append(array)
group1 = []
group2 = []
group3 = []
for i in range(n):
	for j in range(n):
		if (i + j) % 3 == 0:
			group1.append(b[i][j])
		elif (i + j) % 3 == 1:
			group2.append(b[i][j])
		else:
			group3.append(b[i][j])
g1 = Counter(group1)
g2 = Counter(group2)
g3 = Counter(group3)
sum1 = []
sum2 = []
sum3 = []

def cal(l, output):
	for i in range(c):
		s = 0
		for j in l.items():
			s += a[j[0] - 1][i - 1] * j[1]
		output.append(s)
li = [g1, g2, g3]
li2 = [sum1, sum2, sum3]
for i in range(3):
	cal(li[i], li2[i])
cc = list(range(c))
min_sum = 10 ** 10
for (i, j, k) in permutations(cc, 3):
	sum = sum1[i] + sum2[j] + sum3[k]
	if sum < min_sum:
		min_sum = sum
print(min_sum)


from itertools import *
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for c in range(C)]
G = [list(map(int, input().split())) for n in range(N)]
H = [C * [0] for n in range(3)]
for i in range(N):
	for (j, k) in enumerate(G[i]):
		H[(i + j) % 3][k - 1] += 1
ans = float('inf')
for i in permutations(range(C), 3):
	c = 0
	for j in range(3):
		for k in range(C):
			c += D[k][i[j]] * H[j][k]
	ans = min(ans, c)
print(ans)


import collections
import itertools
(n, c) = map(int, input().split())
ds = [list(map(int, input().split())) for _ in range(c)]
colors = [collections.Counter() for _ in range(3)]
for i in range(n):
	for (j, color) in enumerate(map(int, input().split())):
		colors[(i + j) % 3][color - 1] += 1
res = float('inf')
for cs in itertools.permutations(range(c), 3):
	s = 0
	for i in range(3):
		for (k, v) in colors[i].items():
			s += ds[k][cs[i]] * v
	res = min(res, s)
print(res)


(n, c) = map(int, input().split())
D = [tuple(map(int, input().split())) for _ in range(c)]
C = [tuple(map(lambda x: int(x) - 1, input().split())) for _ in range(n)]
dst = [[0, 0, 0] for _ in range(c)]
for ci in range(c):
	for i in range(n):
		for j in range(n):
			c_from = C[i][j]
			dst[ci][(i + j) % 3] += D[c_from][ci]
from itertools import permutations
d = 1000 * 500 * 500
for (p0, p1, p2) in permutations(list(range(c)), 3):
	d = min(d, dst[p0][0] + dst[p1][1] + dst[p2][2])
print(d)


import itertools
(n, cc) = list(map(int, input().split()))
d = [list(map(int, input().split())) for i in range(cc)]
c = [list(map(int, input().split())) for i in range(n)]
counter = [[0 for i in range(cc)] for j in range(3)]
for i in range(n):
	for j in range(n):
		counter[(i + j) % 3][c[i][j] - 1] += 1
m = 250000000
for y in itertools.permutations(range(cc), 3):
	new = 0
	for i in range(3):
		for x in range(cc):
			new += counter[i][x - 1] * d[x - 1][y[i]]
	m = min(m, new)
print(m)


import sys
import heapq, math
from itertools import zip_longest, permutations, combinations, combinations_with_replacement
from itertools import accumulate, dropwhile, takewhile, groupby
from functools import lru_cache
from copy import deepcopy
(N, C) = map(int, input().split())
CM = [list(map(int, input().split())) for _ in range(C)]
NM = [list(map(int, input().split())) for _ in range(N)]
cnt = [[0] * (C + 1) for _ in range(3)]
for i in range(N):
	for j in range(N):
		cnt[(i + j + 2) % 3][NM[i][j]] += 1
ans = 1 << 28
for i in range(1, C + 1):
	for j in range(1, C + 1):
		for k in range(1, C + 1):
			if i == j or j == k or i == k:
				continue
			c = 0
			for l in range(1, C + 1):
				c += cnt[0][l] * CM[l - 1][i - 1]
				c += cnt[1][l] * CM[l - 1][j - 1]
				c += cnt[2][l] * CM[l - 1][k - 1]
			ans = min(ans, c)
print(ans)


import itertools
(N, C) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
memo = [[0 for i in range(C)] for j in range(3)]
for i in range(N):
	for j in range(N):
		cij = c[i][j]
		a = (i + j + 2) % 3
		for k in range(C):
			memo[a][k] += d[cij - 1][k]
ans = 250000001
for (c1, c2, c3) in itertools.permutations(range(C), 3):
	ans = min(ans, memo[0][c1] + memo[1][c2] + memo[2][c3])
print(ans)


from collections import defaultdict
(N, C) = map(int, input().split())
D = [tuple(map(int, input().split())) for _ in range(C)]
d = [defaultdict(int) for i in range(3)]
for i in range(N):
	c = [int(x) for x in input().split()]
	for j in range(N):
		for k in range(C):
			d[(i + j) % 3][k] += D[c[j] - 1][k]
ans = 10 ** 9
for i in range(C):
	for j in range(C):
		for k in range(C):
			if i != j and j != k and (k != i):
				ans = min(ans, d[0][i] + d[1][j] + d[2][k])
print(ans)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time, copy, bisect
from operator import itemgetter
from heapq import heappush, heappop
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7
stdin = sys.stdin
ni = lambda : int(ns())
nf = lambda : float(ns())
na = lambda : list(map(int, stdin.readline().split()))
nb = lambda : list(map(float, stdin.readline().split()))
ns = lambda : stdin.readline().rstrip()
(N, C) = na()
D = [na() for _ in range(C)]
c = [na() for _ in range(N)]
z = {}
o = {}
t = {}
for i in range(1, N + 1):
	for j in range(1, N + 1):
		q = (i + j) % 3
		now = c[i - 1][j - 1] - 1
		if q == 0:
			if now not in list(z.keys()):
				z[now] = 1
			else:
				z[now] += 1
		if q == 1:
			if now not in list(o.keys()):
				o[now] = 1
			else:
				o[now] += 1
		if q == 2:
			if now not in list(t.keys()):
				t[now] = 1
			else:
				t[now] += 1
ans = inf
for (i, j, l) in itertools.permutations(list(range(C)), 3):
	tmp = 0
	for (k, v) in list(z.items()):
		tmp += v * D[k][i]
	for (k, v) in list(o.items()):
		tmp += v * D[k][j]
	for (k, v) in list(t.items()):
		tmp += v * D[k][l]
	ans = min(tmp, ans)
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
A = [list(map(int, input().split())) for i in range(N)]
X = [[0] * C for i in range(3)]
for c in range(C):
	for i in range(N):
		for j in range(N):
			X[(i + j) % 3][c] += D[A[i][j] - 1][c]
P = 10 ** 20
for i in range(C):
	for j in range(C):
		for k in range(C):
			if len(set([i, j, k])) == 3:
				P = min(P, X[0][i] + X[1][j] + X[2][k])
print(P)


(n, c) = map(int, input().split())
D = []
for i in range(c):
	D.append(list(map(int, input().split())))
C = []
for i in range(n):
	C.append(list(map(int, input().split())))
A = [[0] * c for i in range(3)]
for i in range(n):
	for j in range(n):
		a = (i + j) % 3
		A[a][C[i][j] - 1] += 1
ans = 10 ** 100
for a0 in range(c):
	for a1 in range(c):
		for a2 in range(c):
			if a0 == a1 or a1 == a2 or a2 == a0:
				continue
			cnt = 0
			for i in range(c):
				cnt += D[i][a0] * A[0][i]
				cnt += D[i][a1] * A[1][i]
				cnt += D[i][a2] * A[2][i]
			ans = min(cnt, ans)
print(ans)


from itertools import permutations
(N, C) = map(int, input().split())
D = [None] * C
for i in range(C):
	D[i] = list(map(int, input().split()))
c = [None] * N
for i in range(N):
	c[i] = list(map(int, input().split()))
t = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		t[(i + j) % 3][c[i][j] - 1] += 1
ans = 10 ** 12
for p in permutations(range(C), 3):
	tmp = 0
	for i in range(C):
		tmp += D[i][p[0]] * t[0][i]
		tmp += D[i][p[1]] * t[1][i]
		tmp += D[i][p[2]] * t[2][i]
	ans = min(ans, tmp)
print(ans)


import itertools
(n, c) = map(int, input().split())
ld = [list(map(int, input().split())) for i in range(c)]
lc = [list(map(int, input().split())) for i in range(n)]
ct = [[0 for i in range(c)] for i in range(3)]
for i in range(n):
	for j in range(n):
		ct[(i + j + 2) % 3][lc[i][j] - 1] += 1
L = list(itertools.permutations([i for i in range(c)], 3))
ans = []
for i in range(len(L)):
	ct2 = 0
	for j in range(3):
		for k in range(c):
			ct2 += ld[k][L[i][j]] * ct[j][k]
	ans.append(ct2)
print(min(ans))


from collections import Counter
from itertools import permutations
(N, C) = map(int, input().split())
cost = [list(map(int, input().split())) for _ in range(C)]
color = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]
mod3 = {0: [], 1: [], 2: []}
for i in range(N):
	for j in range(N):
		m = (i + j) % 3
		mod3[m].append(color[i][j])
cnts = [Counter(mod3[i]) for i in range(3)]
ans = float('inf')
for p in permutations(range(C), 3):
	cond = 0
	for i in range(3):
		for col in cnts[i].keys():
			cond += cnts[i][col] * cost[col][p[i]]
	ans = min(ans, cond)
print(ans)


import sys
from collections import Counter
from itertools import permutations
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007

def main():
	(N, C) = list(map(int, readline().split()))
	D = [0] * C
	for i in range(C):
		D[i] = list(map(int, readline().split()))
	G = [0] * N
	for i in range(N):
		G[i] = [int(s) - 1 for s in readline().split()]
	counter = [[0] * C for _ in range(3)]
	cost = [[0] * C for _ in range(3)]
	for x in range(N):
		for y in range(N):
			counter[(x + y) % 3][G[x][y]] += 1
	for (cur_cost, cur_counter) in zip(cost, counter):
		for i in range(C):
			for j in range(C):
				cur_cost[i] += cur_counter[j] * D[j][i]
	ans = INF
	for (c1, c2, c3) in permutations(list(range(C)), 3):
		if ans > cost[0][c1] + cost[1][c2] + cost[2][c3]:
			ans = cost[0][c1] + cost[1][c2] + cost[2][c3]
	print(ans)
	return

def __starting_point():
	main()
__starting_point()


(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
board = [list(map(int, input().split())) for _ in range(n)]
cnt = [[0] * c for _ in range(3)]
for i in range(n):
	for j in range(n):
		cnt[(i + j) % 3][board[i][j] - 1] += 1
ans = 10 ** 10
for i in range(c):
	for j in range(c):
		if i == j:
			continue
		for k in range(c):
			if i == k or j == k:
				continue
			tmp = 0
			for l in range(c):
				tmp += d[l][i] * cnt[0][l]
				tmp += d[l][j] * cnt[1][l]
				tmp += d[l][k] * cnt[2][l]
			ans = min(ans, tmp)
print(ans)


(N, C) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
x = [[0] * (C + 1) for _ in range(3)]
for i in range(N):
	for j in range(N):
		x[(i + j + 2) % 3][c[i][j]] += 1
from itertools import permutations
ans = 1 << 32
for ch in permutations(range(1, C + 1), 3):
	ans1 = 0
	for i in range(3):
		for j in range(1, C + 1):
			ans1 += x[i][j] * d[j - 1][ch[i] - 1]
	ans = min(ans, ans1)
print(ans)


from itertools import product
(N, C) = map(int, input().split())
cost = [[int(st) for st in input().split()] for _ in range(C)]
count = {0: {}, 1: {}, 2: {}}
for y in range(N):
	for (x, v) in enumerate(map(int, input().split())):
		rest = (x + y) % 3
		count[rest][v] = 1 + count[rest].get(v, 0)
mincost = 9223372036854775807
for cc in product(*[range(1, C + 1)] * 3):
	if cc[0] != cc[1] and cc[0] != cc[2] and (cc[1] != cc[2]):
		sumcost = 0
		for i in range(3):
			for (cl, cnt) in count[i].items():
				sumcost += cnt * cost[cl - 1][cc[i] - 1]
		mincost = min(sumcost, mincost)
print(mincost)


import sys

def main():
	input = sys.stdin.readline
	(n, c) = map(int, input().split())
	d = [0 for _ in range(c)]
	for i in range(c):
		d[i] = [int(x) for x in input().split()]
	grid = [0 for _ in range(n)]
	for i in range(n):
		grid[i] = [int(x) for x in input().split()]
	(k1, k2, k3) = ([0] * c, [0] * c, [0] * c)
	for i in range(n):
		for j in range(n):
			if (i + j) % 3 == 1:
				k1[grid[i][j] - 1] += 1
			elif (i + j) % 3 == 2:
				k2[grid[i][j] - 1] += 1
			else:
				k3[grid[i][j] - 1] += 1
	(key1, key2, key3) = ([], [], [])
	for i in range(c):
		(sub1, sub2, sub3) = (0, 0, 0)
		for j in range(c):
			if i == j:
				continue
			sub1 += k1[j] * d[j][i]
			sub2 += k2[j] * d[j][i]
			sub3 += k3[j] * d[j][i]
		key1.append([sub1, i])
		key2.append([sub2, i])
		key3.append([sub3, i])
	key1.sort()
	key2.sort()
	key3.sort()
	key1 = key1[:3]
	key2 = key2[:3]
	key3 = key3[:3]
	ans = pow(10, 9)
	for i in range(3):
		for j in range(3):
			for k in range(3):
				if key1[i][1] != key2[j][1] and key2[j][1] != key3[k][1] and (key1[i][1] != key3[k][1]):
					if ans > key1[i][0] + key2[j][0] + key3[k][0]:
						ans = key1[i][0] + key2[j][0] + key3[k][0]
	print(ans)

def __starting_point():
	main()
__starting_point()


from itertools import permutations
(n, cn) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(cn)]
c = [list(map(int, input().split())) for _ in range(n)]
col_count = [[0] * cn for _ in range(3)]
for i in range(n):
	for j in range(n):
		col_count[(i + j + 2) % 3][c[i][j] - 1] += 1
ans = 1000 * n * n
for c123 in permutations(range(cn), 3):
	dsum = 0
	for i in range(3):
		for j in range(cn):
			dsum += d[j][c123[i]] * col_count[i][j]
	ans = min(ans, dsum)
print(ans)


from itertools import product, permutations

def main():
	(N, C) = list(map(int, input().split()))
	D = [list(map(int, input().split())) for _ in range(C)]
	c = [list(map(int, input().split())) for _ in range(N)]
	T = [[0] * C for _ in range(3)]
	for (x, y) in product(list(range(N)), repeat=2):
		r = (x + y) % 3
		for i in range(C):
			T[r][i] += D[c[x][y] - 1][i]
	Q = []
	for j in range(3):
		Q.append(sorted(((t, i) for (i, t) in enumerate(T[j]))))
	m = 10 ** 10
	for (x, y, z) in product(list(range(3)), repeat=3):
		(X, Y, Z) = (Q[0][x], Q[1][y], Q[2][z])
		if X[1] == Y[1] or Y[1] == Z[1] or Z[1] == X[1]:
			continue
		m = min(m, X[0] + Y[0] + Z[0])
	return m
print(main())


import itertools
(N, C) = [int(_) for _ in input().split()]
D = [[int(_) for _ in input().split()] for _ in range(C)]
c = [[int(_) - 1 for _ in input().split()] for _ in range(N)]
grid = [[0] * C for _ in range(3)]
for (i, j) in itertools.product(range(N), repeat=2):
	grid[(i + j) % 3][c[i][j]] += 1
ans = float('inf')
for color_after in itertools.permutations(range(C), 3):
	ans = min(ans, sum([sum([grid[g][color_before] * D[color_before][color_after[g]] for color_before in range(C)]) for g in range(3)]))
print(ans)


(n, C) = map(int, input().split())
d = [[int(i) for i in input().split()] for _ in range(C)]
c = [[int(i) - 1 for i in input().split()] for _ in range(n)]
cnt = [[0] * C for _ in range(3)]
for i in range(n):
	for j in range(n):
		for k in range(C):
			cnt[(i + j) % 3][k] += d[c[i][j]][k]
ans = float('inf')
for i in range(C):
	for j in range(C):
		if i == j:
			continue
		for k in range(C):
			if i == k or j == k:
				continue
			ans = min(ans, cnt[0][i] + cnt[1][j] + cnt[2][k])
print(ans)


from itertools import permutations
(N, C) = map(int, input().split())
D = list()
for _ in range(C):
	D.append(list(map(int, input().split())))
c = list()
for _ in range(N):
	c.append(list(map(int, input().split())))
sw = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		idc = c[i][j] - 1
		for _idc in range(C):
			sw[(i + j) % 3][_idc] += D[idc][_idc]
ans = 10 ** 9
for p in permutations(range(C), 3):
	tmp = 0
	for (idx, q) in enumerate(p):
		tmp += sw[idx][q]
	if ans > tmp:
		ans = tmp
print(ans)


from collections import defaultdict
import itertools
(N, C) = map(int, input().split())
D = [[0] * C for _ in range(C)]
for i in range(C):
	D[i] = list((int(d) for d in input().split()))
dict_c = [defaultdict(int) for _ in range(3)]
for i in range(N):
	c = list((int(x) for x in input().split()))
	for j in range(N):
		dict_c[(i + j) % 3][c[j] - 1] += 1
list_C = list(range(C))
ans = 10 ** 18
for (p, q, r) in itertools.permutations(list_C, 3):
	tmp = 0
	for (i, j) in enumerate((p, q, r)):
		for (m, n) in dict_c[i].items():
			tmp += D[m][j] * n
	ans = min(ans, tmp)
print(ans)


(n, C) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(n)]
a = [[0] * C for _ in range(3)]
for i in range(n):
	for j in range(n):
		a[(i + j) % 3][c[i][j] - 1] += 1
b = [[0] * C for _ in range(3)]
for i in range(3):
	for j in range(C):
		v = 0
		for k in range(C):
			v += a[i][k] * d[k][j]
		b[i][j] = v
r = 10 ** 9
for i in range(C):
	for j in range(C):
		for k in range(C):
			if len({i, j, k}) == 3:
				r = min(r, b[0][i] + b[1][j] + b[2][k])
print(r)


import itertools
(N, C) = map(int, input().split(' '))
D = [list(map(int, input().split(' '))) for i in [0] * C]
c = [list(map(int, input().split(' '))) for i in [0] * N]
l = [[], [], []]
n = 0
for i in range(N):
	for j in range(i + 1):
		l[n].append(c[i - j][j])
	n = (n + 1) % 3
for i in range(N - 1):
	for j in range(N - i - 1):
		l[n].append(c[i + j + 1][N - j - 1])
	n = (n + 1) % 3
(d1, d2, d3) = [[sum([D[j - 1][i] for j in l[n]]) for i in range(C)] for n in range(3)]
ans = 1000 * 500 * 500
colors = list(range(C))
for (c1, c2, c3) in itertools.permutations(colors, 3):
	ans = min(ans, d1[c1] + d2[c2] + d3[c3])
print(ans)


(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for i in range(c)]
g = [list(map(int, input().split())) for i in range(n)]
cost = [[0] * c for i in range(3)]
for i in range(3):
	for j in range(c):
		for a in range(n):
			for b in range(n):
				if (a + b) % 3 == i:
					cost[i][j] += d[g[a][b] - 1][j]
ret = 10 ** 10
for i in range(c):
	for j in range(c):
		for k in range(c):
			if i == j or j == k or k == i:
				continue
			ret = min(ret, cost[0][i] + cost[1][j] + cost[2][k])
print(ret)


from collections import defaultdict
(N, C) = list(map(int, input().split()))
D = defaultdict(int)
t = defaultdict(int)
for i in range(C):
	s = list(map(int, input().split()))
	for j in range(C):
		D[i, j] = s[j]
for i in range(N):
	s = list(map(int, input().split()))
	for j in range(N):
		t[(i + j) % 3, s[j] - 1] += 1
ans = 1 << 30
for i in range(C):
	for j in range(C):
		for k in range(C):
			if i != j != k != i:
				res = 0
				for l in range(C):
					res += D[l, i] * t[0, l]
				for l in range(C):
					res += D[l, j] * t[1, l]
				for l in range(C):
					res += D[l, k] * t[2, l]
				ans = min(ans, res)
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
grid = [list(map(int, input().split())) for _ in range(N)]
D0 = {i: 0 for i in range(C)}
D1 = {i: 0 for i in range(C)}
D2 = {i: 0 for i in range(C)}
for i in range(N):
	for j in range(N):
		if (i + j) % 3 == 0:
			D0[grid[i][j] - 1] += 1
		elif (i + j) % 3 == 1:
			D1[grid[i][j] - 1] += 1
		elif (i + j) % 3 == 2:
			D2[grid[i][j] - 1] += 1
m = int(100000000000.0) + 23
for i in range(C):
	for j in range(C):
		for k in range(C):
			if i != j and j != k and (k != i):
				differ = 0
				for l in range(C):
					differ += D0[l] * D[l][i]
					differ += D1[l] * D[l][j]
					differ += D2[l] * D[l][k]
				if m > differ:
					m = differ
print(m)


from itertools import permutations, product
(N, C) = list(map(int, input().split()))
D = [[0] * (C + 1)] + [[0] + list(map(int, input().split())) for _ in range(C)]
c = [[0] * (N + 1)] + [[0] + list(map(int, input().split())) for _ in range(N)]
mod3 = [[0] * (C + 1) for _ in range(3)]
for (i, j) in product(range(1, N + 1), range(1, N + 1)):
	mod3[(i + j) % 3][c[i][j]] += 1
answer = 1000 * 500 * 500
for colors in permutations(range(1, C + 1), 3):
	temp = sum([sum([D[i][colors[m]] * n for (i, n) in enumerate(mod3[m])]) for m in range(3)])
	answer = min(answer, temp)
print(answer)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
from collections import Counter
t = [Counter([c[i][j] for i in range(N) for j in range(N) if (i + j) % 3 == m]) for m in range(3)]
ans = 10 ** 9
for i in range(C):
	for j in range(C):
		if i == j:
			continue
		for k in range(C):
			if i == k or j == k:
				continue
			d = 0
			for before in range(C):
				d += D[before][i] * t[0][before + 1]
				d += D[before][j] * t[1][before + 1]
				d += D[before][k] * t[2][before + 1]
			ans = min(ans, d)
print(ans)


from itertools import permutations
from collections import Counter

def inpl():
	return list(map(int, input().split()))
(N, C) = inpl()
D = [inpl() for _ in range(C)]
G = [Counter() for _ in range(3)]
for i in range(1, N + 1):
	for (j, c) in enumerate(inpl(), start=1):
		G[(i + j) % 3][c - 1] += 1
ans = 10 ** 9
for (p, q, r) in permutations(range(C), 3):
	tmp = 0
	for c in range(C):
		tmp += D[c][p] * G[0][c] + D[c][q] * G[1][c] + D[c][r] * G[2][c]
	ans = min(ans, tmp)
print(ans)


(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
l = [[i for i in [0] * c] for _ in range(3)]
for i in range(n):
	t = list(map(int, input().split()))
	for j in range(n):
		l[(i + j) % 3][t[j] - 1] += 1
a = 10 ** 18
for i in range(c):
	for j in range(c):
		for k in range(c):
			if i == j or j == k or k == i:
				continue
			a = min(a, sum((d[x][i] * l[0][x] + d[x][j] * l[1][x] + d[x][k] * l[2][x] for x in range(c))))
print(a)


import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(10 ** 7)
INF = float('inf')

def I():
	return int(input())

def F():
	return float(input())

def SS():
	return input()

def LI():
	return [int(x) for x in input().split()]

def LI_():
	return [int(x) - 1 for x in input().split()]

def LF():
	return [float(x) for x in input().split()]

def LSS():
	return input().split()

def resolve():
	(N, C) = LI()
	D = [LI() for _ in range(C)]
	c = [LI_() for _ in range(N)]
	a = [[0] * C for _ in range(3)]
	for (i, j) in itertools.product(list(range(N)), repeat=2):
		for k in range(C):
			a[(i + j) % 3][k] += D[c[i][j]][k]
	ans = INF
	for (i, j, k) in itertools.permutations(list(range(C)), 3):
		ans = min(a[0][i] + a[1][j] + a[2][k], ans)
	print(ans)

def __starting_point():
	resolve()
__starting_point()


(N, C) = [int(i) for i in input().split()]
D = [[int(j) for j in input().split()] for i in range(C)]
c_temp = [[int(j) - 1 for j in input().split()] for i in range(N)]
c = [[0 for i in range(C)] for j in range(3)]
for i in range(N):
	for j in range(N):
		c[(i + j) % 3][c_temp[i][j]] += 1
min = 10 ** 15
for i in [ii for ii in range(C)]:
	for j in [jj for jj in range(C) if jj != i]:
		for k in [kk for kk in range(C) if kk != i and kk != j]:
			count = sum([D[x][i] * c[0][x] + D[x][j] * c[1][x] + D[x][k] * c[2][x] for x in range(C)])
			if min > count:
				min = count
print(min)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
E = [list(map(int, input().split())) for i in range(N)]
from collections import Counter
ctrs = [Counter() for _ in range(3)]
for (i, row) in enumerate(E):
	for (j, c) in enumerate(row):
		ctrs[(i + j) % 3][c] += 1
ans = float('inf')
from itertools import permutations
for ptn in permutations(range(1, C + 1), 3):
	t = 0
	for (p, c) in zip(ptn, ctrs):
		for (k, v) in c.items():
			t += D[k - 1][p - 1] * v
	ans = min(ans, t)
print(ans)


def main():
	(N, C) = map(int, input().split())
	D = [list(map(int, input().split())) for _ in range(C)]
	c = [list(map(int, input().split())) for _ in range(N)]
	cost = [[0] * C for j in range(3)]
	for k in range(C):
		for i in range(N):
			for j in range(N):
				cost[(i + j) % 3][k] += D[c[i][j] - 1][k]
	ans = float('inf')
	for i in range(C):
		for j in range(C):
			for k in range(C):
				if i != j and j != k and (k != i):
					ans = min(ans, cost[0][i] + cost[1][j] + cost[2][k])
	print(ans)
main()


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
cst = [[0, 0, 0] for i in range(C)]
for i in range(N):
	for j in range(N):
		cst[c[i][j] - 1][(i + j) % 3] += 1
ans = 10 ** 10
for i in range(C):
	for j in range(C):
		for k in range(C):
			if i == j or i == k or j == k:
				continue
			x = [i, j, k]
			a = 0
			for l in range(3):
				for m in range(C):
					a += D[m][x[l]] * cst[m][l]
			ans = min(ans, a)
print(ans)


from itertools import permutations
(N, C) = map(int, input().split())
D = []
for _ in range(C):
	Ds = list(map(int, input().split()))
	D.append(Ds)
grid = []
for _ in range(N):
	c = list(map(lambda x: int(x) - 1, input().split()))
	grid.append(c)
color = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		color[(i + j) % 3][grid[i][j]] += 1
INF = 10 ** 9
ans = INF
for cols in permutations(range(C), 3):
	temp = 0
	for (i, Y) in enumerate(cols):
		for (X, cnt) in enumerate(color[i]):
			temp += D[X][Y] * cnt
	ans = min(ans, temp)
print(ans)


from itertools import permutations
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
X = [list(map(int, input().split())) for _ in range(N)]
memo = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		k = (i + j + 2) % 3
		memo[k][X[i][j] - 1] += 1
ans = 10 ** 9 + 7
for c in permutations(range(C), 3):
	cost = 0
	for n in range(3):
		for j in range(C):
			cost += D[j][c[n]] * memo[n][j]
	ans = min(ans, cost)
print(ans)


def main():
	(n, nc) = list(map(int, input().split()))
	d = [list(map(int, input().split())) for i in range(nc)]
	c = [list(map(int, input().split())) for i in range(n)]
	cnt = [[0 for _ in range(nc)] for eta in range(3)]
	for i in range(n):
		for j in range(n):
			eta = (i + j) % 3
			cnt[eta][c[i][j] - 1] += 1
	iwamin = 10 ** 9
	for c1 in range(nc):
		for c2 in range(nc):
			for c3 in range(nc):
				if len(set([c1, c2, c3])) < 3:
					continue
				iwa = 0
				for c4 in range(nc):
					iwa += cnt[0][c4] * d[c4][c1]
					iwa += cnt[1][c4] * d[c4][c2]
					iwa += cnt[2][c4] * d[c4][c3]
				iwamin = min(iwamin, iwa)
	print(iwamin)

def __starting_point():
	main()
__starting_point()


import itertools
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [[int(s) - 1 for s in input().split()] for _ in range(N)]
m0 = [0] * C
m1 = [0] * C
m2 = [0] * C
for (i, j) in itertools.product(range(N), repeat=2):
	if (i + j) % 3 == 0:
		m0[c[i][j]] += 1
	if (i + j) % 3 == 1:
		m1[c[i][j]] += 1
	if (i + j) % 3 == 2:
		m2[c[i][j]] += 1
ans = float('inf')
for (x, y, z) in itertools.permutations(range(C), 3):
	point = 0
	for i in range(C):
		point += D[i][x] * m0[i]
	for i in range(C):
		point += D[i][y] * m1[i]
	for i in range(C):
		point += D[i][z] * m2[i]
	ans = min(ans, point)
print(ans)


(N, C) = map(int, input().split())
D = []
c = []
for i in range(C):
	D.append(list(map(int, input().split())))
for i in range(N):
	c.append(list(map(int, input().split())))
d = {}
d[0] = {}
d[1] = {}
d[2] = {}
for i in range(C):
	d[0][i] = 0
	d[1][i] = 0
	d[2][i] = 0
for k in range(C):
	for i in range(N):
		for j in range(N):
			d[(i + j) % 3][k] += D[c[i][j] - 1][k]
import itertools
ans = 10 ** 50
l = []
for i in range(C):
	l.append(i)
for li in itertools.permutations(l, 3):
	ans = min(ans, d[0][li[0]] + d[1][li[1]] + d[2][li[2]])
print(ans)


(N, C) = map(int, input().split())
D = [[int(i) for i in input().split()] for i in range(C)]
L = [[0] * C for i in range(3)]
for i in range(N):
	X = [int(i) for i in input().split()]
	for j in range(N):
		L[(i + j) % 3][X[j] - 1] += 1
ans = float('inf')
for i in range(C):
	for j in range(C):
		for k in range(C):
			if i != j and j != k and (k != i):
				tmp = 0
				for x in range(C):
					tmp += L[0][x] * D[x][i] + L[1][x] * D[x][j] + L[2][x] * D[x][k]
				ans = min(ans, tmp)
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for k in range(C)]
G = [list(map(int, input().split())) for k in range(N)]
M = [[0, 0, 0] for k in range(C)]
for x in range(N):
	for y in range(N):
		M[G[x][y] - 1][(x + y) % 3] += 1
ans = 10 ** 9
for p in range(C):
	for q in range(C):
		for r in range(C):
			if p != q and q != r and (r != p):
				t = 0
				for s in range(C):
					t += D[s][p] * M[s][0] + D[s][q] * M[s][1] + D[s][r] * M[s][2]
				ans = min(t, ans)
print(ans)


import itertools
(n, cs) = map(int, input().split())
d = [list(map(int, input().split())) for i in range(cs)]
c = [list(map(int, input().split())) for i in range(n)]
color_count = [[0] * cs for i in range(3)]
for (i, j) in itertools.product(range(n), repeat=2):
	color_count[(i + j) % 3][c[i][j] - 1] += 1
ans = 10 ** 20
for t in itertools.permutations(range(cs), 3):
	s = 0
	for l in range(3):
		for m in range(cs):
			s += color_count[l][m] * d[m][t[l]]
	ans = min(ans, s)
print(ans)


import sys
from itertools import permutations
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7

def resolve():
	(n, c) = list(map(int, input().split()))
	D = [list(map(int, input().split())) for _ in range(c)]
	grid = [list(map(int, input().split())) for _ in range(n)]
	col_cnt = [[0] * c for _ in range(3)]
	for i in range(n):
		for j in range(n):
			col = grid[i][j] - 1
			col_cnt[(i + j + 2) % 3][col] += 1
	res = f_inf
	for pattern in permutations(list(range(c)), 3):
		cost = 0
		for (idx, col) in enumerate(pattern):
			for k in range(c):
				cnt = col_cnt[idx][k]
				cost += D[k][col] * cnt
		res = min(res, cost)
	print(res)

def __starting_point():
	resolve()
__starting_point()


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
c = [list(map(int, input().split())) for i in range(N)]
col = [[0] * C for i in range(3)]
for i in range(N):
	ci = c[i]
	for j in range(N):
		cc = col[(i + j) % 3]
		dd = D[ci[j] - 1]
		for k in range(C):
			cc[k] += dd[k]
ans = 10 ** 18
c0 = col[0]
c1 = col[1]
c2 = col[2]
for i in range(C):
	for j in range(C):
		if i == j:
			continue
		for k in range(C):
			if i == k or j == k:
				continue
			ans = min(ans, c0[i] + c1[j] + c2[k])
print(ans)


(N, C) = list(map(int, input().split()))
D = [[0] * C for i in range(C)]
for i in range(C):
	D[i] = list(map(int, input().split()))
groups = [[0] * C for i in range(3)]
for i in range(N):
	line = list(map(int, input().split()))
	for j in range(len(line)):
		groups[(i + j) % 3][line[j] - 1] += 1
pattern = [[[0] * 2 for j in range(C)] for i in range(3)]
for i in range(len(groups)):
	for j in range(C):
		iwakan = 0
		for k in range(len(groups[i])):
			iwakan += groups[i][k] * D[k][j]
		pattern[i][j][0] = iwakan
		pattern[i][j][1] = j
for i in range(len(pattern)):
	pattern[i] = sorted(pattern[i], key=lambda x: x[0])
ans = 10 ** 9 + 7
for a in range(3):
	for b in range(3):
		if pattern[0][a][1] == pattern[1][b][1]:
			continue
		for c in range(3):
			if pattern[0][a][1] == pattern[2][c][1]:
				continue
			if pattern[1][b][1] == pattern[2][c][1]:
				continue
			val = pattern[0][a][0] + pattern[1][b][0] + pattern[2][c][0]
			if val < ans:
				ans = val
print(ans)


from itertools import permutations
INF = 10 ** 18
(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
a = [list(map(int, input().split())) for _ in range(n)]
dp = [[0 for _ in range(c)] for i in range(3)]
for i in range(n):
	for j in range(n):
		dp[(i + j) % 3][a[i][j] - 1] += 1
li = list(permutations(list(range(c)), 3))
fans = INF
for (i, j, k) in li:
	ans = 0
	for x in range(c):
		ans += dp[0][x] * d[x][i]
		ans += dp[1][x] * d[x][j]
		ans += dp[2][x] * d[x][k]
	fans = min(fans, ans)
print(fans)


(n, C) = map(int, input().split())
d = []
for i in range(C):
	d.append(list(map(int, input().split())))
c = []
for i in range(n):
	c.append(list(map(int, input().split())))
c0 = {}
c1 = {}
c2 = {}
for i in range(0, n * 2 - 1, 3):
	for j in range(max(0, i - n + 1), min(n, i + 1)):
		c0.setdefault(c[j][i - j], 0)
		c0[c[j][i - j]] += 1
for i in range(1, n * 2 - 1, 3):
	for j in range(max(0, i - n + 1), min(n, i + 1)):
		c1.setdefault(c[j][i - j], 0)
		c1[c[j][i - j]] += 1
for i in range(2, n * 2 - 1, 3):
	for j in range(max(0, i - n + 1), min(n, i + 1)):
		c2.setdefault(c[j][i - j], 0)
		c2[c[j][i - j]] += 1
D = []
for i in range(C):
	for j in range(C):
		for k in range(C):
			if i == j or j == k or k == i:
				continue
			temp = 0
			for (p, q) in c0.items():
				temp += d[p - 1][i] * q
			for (p, q) in c1.items():
				temp += d[p - 1][j] * q
			for (p, q) in c2.items():
				temp += d[p - 1][k] * q
			D.append(temp)
print(min(D))


(n, c) = map(int, input().split())
d = [[int(i) for i in input().split()] for _ in range(c)]
lc = [[int(i) - 1 for i in input().split()] for _ in range(n)]
ans = float('inf')
dp = [[0] * c for i in range(3)]
for C in range(c):
	for y in range(n):
		for x in range(n):
			if lc[y][x] != c:
				dp[(y + x) % 3][C] += d[lc[y][x]][C]
for c0 in range(c):
	for c1 in range(c):
		if c0 == c1:
			continue
		for c2 in range(c):
			if c0 == c2 or c1 == c2:
				continue
			ans = min(ans, dp[0][c0] + dp[1][c1] + dp[2][c2])
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
grid = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		tmp = (i + j) % 3
		for d in range(C):
			grid[tmp][d] += D[c[i][j] - 1][d]
print(min([grid[0][x] + grid[1][y] + grid[2][z] for x in range(C) for y in range(C) for z in range(C) if x != y and y != z and (z != x)]))


memo_mod = [[-1] * 31 for _ in range(3)]
memo_app = [[0] * 31 for _ in range(3)]
(N, C) = list(map(int, input().split()))
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
fa = float('inf')
for i in range(N):
	for j in range(N):
		memo_app[(i + j) % 3][c[i][j]] += 1
for mod0 in range(1, C + 1):
	for mod1 in range(1, C + 1):
		if mod0 == mod1:
			continue
		for mod2 in range(1, C + 1):
			if mod1 == mod2 or mod2 == mod0:
				continue
			else:
				ans = 0
				if memo_mod[0][mod0] == -1:
					tmp = 0
					for idx in range(1, C + 1):
						tmp += memo_app[0][idx] * D[idx - 1][mod0 - 1]
					ans += tmp
				else:
					ans += memo_mod[0][mod0]
				if memo_mod[1][mod1] == -1:
					tmp = 0
					for idx in range(1, C + 1):
						tmp += memo_app[1][idx] * D[idx - 1][mod1 - 1]
					ans += tmp
				else:
					ans += memo_mod[1][mod1]
				if memo_mod[2][mod2] == -1:
					tmp = 0
					for idx in range(1, C + 1):
						tmp += memo_app[2][idx] * D[idx - 1][mod2 - 1]
					ans += tmp
				else:
					ans += memo_mod[2][mod2]
				fa = min(fa, ans)
print(fa)


import sys

def input():
	return sys.stdin.readline().strip()
sys.setrecursionlimit(20000000)
MOD = 10 ** 9 + 7
INF = float('inf')

def main():
	(N, C) = list(map(int, input().split()))
	D = [list(map(int, input().split())) for _ in range(C)]
	c = [list(map(int, input().split())) for _ in range(N)]
	R = [[] for _ in range(3)]
	for i in range(N):
		for j in range(N):
			r = i + 1 + (j + 1)
			if r % 3 == 0:
				R[0].append(c[i][j])
			elif r % 3 == 1:
				R[1].append(c[i][j])
			else:
				R[2].append(c[i][j])
	Diff = [[] for _ in range(3)]
	for i in range(3):
		l = len(R[i])
		for color in range(C):
			cnt = 0
			for j in range(l):
				cnt += D[R[i][j] - 1][color]
			Diff[i].append(cnt)
	answer = INF
	for i in range(C):
		for j in range(C):
			for k in range(C):
				if i == j or j == k or k == i:
					continue
				else:
					ans = Diff[0][i] + Diff[1][j] + Diff[2][k]
					if ans < answer:
						answer = ans
	print(answer)

def __starting_point():
	main()
__starting_point()


from itertools import permutations
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
dp = {k: [sum((D[c[i][j] - 1][k - 1] if (i + j) % 3 == m else 0 for i in range(N) for j in range(N))) for m in range(3)] for k in range(1, C + 1)}
ans = min((dp[i][0] + dp[j][1] + dp[k][2] for (i, j, k) in permutations(range(1, C + 1), 3)))
print(ans)


from itertools import permutations
import numpy as np
(N, C) = map(int, input().split())
D = np.ndarray((C, C), dtype=int)
c = np.ndarray((N, N), dtype=int)
for i in range(C):
	D[i] = list(map(int, input().split()))
for i in range(N):
	c[i] = list(map(int, input().split()))
c -= 1
acc = np.zeros((3, C), dtype=int)
for i in range(N):
	for j in range(N):
		acc[(i + j) % 3] += D[c[i][j]]
ans = float('inf')
for (i, j, k) in permutations(range(C), r=3):
	ans = min(ans, acc[0][i] + acc[1][j] + acc[2][k])
print(ans)


from collections import Counter
from itertools import product, permutations

def main():
	(n, c) = map(int, input().split())
	D = [list(map(int, input().split())) for _ in range(c)]
	C = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)]
	group = [Counter([C[i][j] for (i, j) in product(range(n), range(n)) if (i + j + 2) % 3 == k]) for k in range(3)]
	ans = float('inf')
	for color in permutations(range(c), 3):
		diff = 0
		for i in range(3):
			diff += sum((D[before_color][color[i]] * count for (before_color, count) in group[i].items()))
		ans = min(ans, diff)
	print(ans)
main()


import sys
from itertools import permutations
input = sys.stdin.readline

def main():
	(N, C) = list(map(int, input().split()))
	D = [None] * C
	for i in range(C):
		D[i] = tuple(map(int, input().split()))
	A = [None] * N
	for i in range(N):
		A[i] = tuple(map(int, input().split()))
	R = [[0] * C for _ in range(3)]
	for i in range(N):
		for j in range(N):
			R[(i + j + 2) % 3][A[i][j] - 1] += 1
	cost = [[0] * C for _ in range(3)]
	for r in range(3):
		for Y in range(C):
			tmp = 0
			for (X, num) in enumerate(R[r]):
				tmp += D[X][Y] * num
			cost[r][Y] = tmp
	ans = float('inf')
	for (c0, c1, c2) in permutations(list(range(C)), r=3):
		ans = min(ans, cost[0][c0] + cost[1][c1] + cost[2][c2])
	print(ans)

def __starting_point():
	main()
__starting_point()


from collections import defaultdict as ddict
tot = 10 ** 12
(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
clr = [list(map(int, input().split())) for _ in range(n)]
l = [ddict(int) for _ in range(3)]
for y in range(n):
	for x in range(n):
		l[(x + y) % 3][clr[y][x]] += 1
for c1 in range(c):
	for c2 in range(c):
		if c1 == c2:
			continue
		for c3 in range(c):
			if c1 == c3 or c2 == c3:
				continue
			ctot = 0
			cl = [c1, c2, c3]
			for i in range(3):
				for x in l[i]:
					ctot += d[x - 1][cl[i]] * l[i][x]
			if tot > ctot:
				tot = ctot
print(tot)


(n, c) = map(int, input().split())
d = []
for i in range(c):
	d.append(list(map(int, input().split())))
l = []
for i in range(n):
	l.append(list(map(int, input().split())))
p = [[0 for j in range(c)] for i in range(3)]
for i in range(n):
	for j in range(n):
		p[(i + 1 + j + 1) % 3][l[i][j] - 1] += 1
ans = 10 ** 10
for i in range(c):
	for j in range(c):
		for k in range(c):
			if i != j and i != k and (j != k):
				t = 0
				for x in range(c):
					t += d[x][i] * p[0][x]
					t += d[x][j] * p[1][x]
					t += d[x][k] * p[2][x]
				ans = min(ans, t)
print(ans)


(n, c) = map(int, input().split())
dl = [list(map(int, input().split())) for _ in range(c)]
nl = [list(map(int, input().split())) for _ in range(n)]
ax = [[0 for i in range(c)] for j in range(3)]
for i in range(n):
	for j in range(n):
		x = (i + j) % 3
		ax[x][nl[i][j] - 1] += 1
l = list(range(0, c))
import itertools
ll = list(itertools.permutations(l, 3))
res = float('inf')
for i in ll:
	temp = 0
	for j in range(c):
		temp += ax[0][j] * dl[j][i[0]]
		temp += ax[1][j] * dl[j][i[1]]
		temp += ax[2][j] * dl[j][i[2]]
	res = min(res, temp)
print(res)


from itertools import permutations
from collections import defaultdict
(N, C) = list(map(int, input().split()))
D = [list(map(int, input().split())) for _ in range(C)]
remains = {0: defaultdict(int), 1: defaultdict(int), 2: defaultdict(int)}
for i in range(1, N + 1):
	line = list(map(int, input().split()))
	for j in range(N):
		remains[(i + j + 1) % 3][line[j]] += 1
INF = float('inf')
answer = INF
for choice in permutations(range(1, C + 1), 3):
	_answer = 0
	for (i, c) in enumerate(choice):
		_answer += sum([D[r - 1][c - 1] * remains[i][r] for r in remains[i] if c != r])
	answer = min(answer, _answer)
print(answer)


import sys
from itertools import permutations, combinations
(n, c) = map(int, sys.stdin.readline().split())
d = [[int(x) for x in sys.stdin.readline().split()] for _ in range(c)]
grid = [[int(x) - 1 for x in sys.stdin.readline().split()] for _ in range(n)]
cost = [[0] * c for _ in range(3)]
for i in range(n):
	for j in range(n):
		k = (i + j) % 3
		for l in range(c):
			cost[k][l] += d[grid[i][j]][l]

def main():
	res = []
	for comb in combinations(range(c), 3):
		for (i, j, k) in permutations(comb):
			res.append(cost[0][i] + cost[1][j] + cost[2][k])
	print(min(res))
main()


(N, C) = map(int, input().split())
D = [tuple(map(int, input().split())) for _ in range(C)]
color = [tuple(map(int, input().split())) for _ in range(N)]
wrongness = [[0, 0, 0] for _ in range(C)]
for c in range(C):
	for i in range(N):
		for j in range(N):
			wrongness[c][(i + j) % 3] += D[color[i][j] - 1][c]
ans = 10 ** 18
for c1 in range(C):
	for c2 in range(C):
		for c3 in range(C):
			if c1 == c2 or c2 == c3 or c3 == c1:
				continue
			ans = min(ans, wrongness[c1][0] + wrongness[c2][1] + wrongness[c3][2])
print(ans)


(n, c) = list(map(int, input().split()))
d = [list(map(int, input().split())) for i in range(c)]
c_ = [list(map(int, input().split())) for i in range(n)]
g = [[] for i in range(3)]
for i in range(n):
	for j in range(n):
		g[(i + j + 2) % 3].append(c_[i][j] - 1)
f = [[] for i in range(3)]
for i in range(3):
	for j in range(c):
		x = 0
		for k in g[i]:
			x += d[k][j]
		f[i].append((j, x))
	f[i] = sorted(f[i], key=lambda x: x[1])[:3]
ans = []
for i in f[0]:
	for j in f[1]:
		for k in f[2]:
			if i[0] != j[0] and k[0] != j[0] and (i[0] != k[0]):
				ans.append(i[1] + j[1] + k[1])
print(min(ans))


(N, c) = map(int, input().split())
D = [[int(i) for i in input().split()] for j in range(c)]
C = [[int(i) for i in input().split()] for j in range(N)]
A = [[0 for i in range(c)] for j in range(3)]
for i in range(N):
	for j in range(N):
		for k in range(c):
			A[(i + j) % 3][k] += D[C[i][j] - 1][k]
ans = 1000000000.0
for i in range(c):
	for j in range(i):
		for k in range(j):
			for l in range(3):
				ans = min(ans, A[l][i] + A[(l + 1) % 3][j] + A[(l + 2) % 3][k], A[l][i] + A[(l - 1) % 3][j] + A[(l - 2) % 3][k])
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
color = [list(map(int, input().split())) for _ in range(N)]
cs = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		amari = (i + j) % 3
		cs[amari][color[i][j] - 1] += 1
ans = 500 * 500 * 1000
for i in range(C):
	for j in range(C):
		if i == j:
			continue
		for k in range(C):
			if i == k or j == k:
				continue
			now = 0
			for ci in range(C):
				now += D[ci][i] * cs[0][ci]
				now += D[ci][j] * cs[1][ci]
				now += D[ci][k] * cs[2][ci]
			ans = min(ans, now)
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
G = [list(map(int, input().split())) for i in range(N)]
cost = [[0 for j in range(C)] for i in range(3)]
for i in range(N):
	for j in range(N):
		rem = (i + j + 2) % 3
		x = G[i][j] - 1
		for y in range(C):
			cost[rem][y] += D[x][y]
ans = float('inf')
for i in range(C):
	for j in range(C):
		if i == j:
			continue
		for k in range(C):
			if i == k or j == k:
				continue
			ans = min(ans, cost[0][i] + cost[1][j] + cost[2][k])
print(ans)


from collections import Counter
from itertools import permutations
(n, c) = list(map(int, input().split()))
d = [list(map(int, input().split())) for _ in range(c)]
ci = [[] for _ in range(3)]
for i in range(n):
	cl = list(map(int, input().split()))
	for j in range(3):
		ci[(i + j) % 3].extend(cl[j::3])
for i in range(3):
	ci[i] = Counter(ci[i])

def iwa(cols):
	ret = 0
	for i in range(3):
		for (x, v) in list(ci[i].items()):
			ret += v * d[x - 1][cols[i]]
	return ret
L = list(permutations(list(range(c)), 3))
ret = 500 * 500 * 1000
for cols in L:
	ret = min(ret, iwa(cols))
print(ret)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
c = [list(map(int, input().split())) for i in range(N)]
col = [[0 for i in range(C + 1)] for j in range(3)]
for i in range(N):
	for j in range(N):
		col[(i + j + 2) % 3][c[i][j]] += 1
ans = 10 ** 15
import itertools
PRD = list(itertools.product([i for i in range(C)], repeat=3))
for i in range(len(PRD)):
	newc = [PRD[i][0], PRD[i][1], PRD[i][2]]
	if newc[0] == newc[1] or newc[1] == newc[2] or newc[2] == newc[0]:
		continue
	cost = 0
	for j in range(3):
		for k in range(C):
			cost += col[j][k + 1] * D[k][newc[j]]
	ans = min(cost, ans)
print(ans)


(N, C) = list(map(int, input().split()))
discomforts = [[0] * (N + 1)]
for _ in range(C):
	row = [0]
	row.extend(list(map(int, input().split())))
	discomforts.append(row)
grid = [[0] * (N + 1)]
for _ in range(N):
	row = [0]
	row.extend(list(map(int, input().split())))
	grid.append(row)
color_counts = [[0] * (C + 1) for i in range(3)]
for i in range(1, N + 1):
	for j in range(1, N + 1):
		color_counts[(i + j) % 3][grid[i][j]] += 1
ans = float('inf')
for c0 in range(1, C + 1):
	for c1 in range(1, C + 1):
		for c2 in range(1, C + 1):
			if c0 != c1 and c1 != c2 and (c2 != c0):
				total = 0
				for i in range(1, C + 1):
					total += discomforts[i][c0] * color_counts[0][i]
					total += discomforts[i][c1] * color_counts[1][i]
					total += discomforts[i][c2] * color_counts[2][i]
				ans = min(ans, total)
print(ans)


import itertools
(N, C) = map(int, input().split())
D = []
for i in range(C):
	Ds = list(map(int, input().split()))
	D.append(Ds)
c = []
for i in range(N):
	cs = list(map(int, input().split()))
	cs = [c - 1 for c in cs]
	c.append(cs)
ns = [[0] * C for i in range(3)]
for i in range(N):
	for j in range(N):
		ns[(i + j) % 3][c[i][j]] += 1
rs = []
for (c0, c1, c2) in itertools.permutations(range(C), 3):
	r = 0
	for i in range(C):
		r += D[i][c0] * ns[0][i]
		r += D[i][c1] * ns[1][i]
		r += D[i][c2] * ns[2][i]
	rs.append(r)
r = min(rs)
print(r)


import itertools
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
G = [list(map(int, input().split())) for i in range(N)]
colors = [[0 for c in range(C)] for p in range(3)]
for y in range(N):
	for x in range(N):
		c = G[y][x] - 1
		colors[(x + y) % 3][c] += 1
ans = float('inf')
for ptn in itertools.permutations(range(C), 3):
	tmp = 0
	for (p, ct) in enumerate(ptn):
		for cf in range(C):
			tmp += D[cf][ct] * colors[p][cf]
	ans = min(ans, tmp)
print(ans)


import itertools, operator
(N, C) = map(int, input().split())
Ds = [list(map(int, input().split())) for i in range(C)]
cs = [list(map(int, input().split())) for i in range(N)]
Ds = list(map(list, zip(*Ds)))
cnts = [[0] * C for k in range(3)]
for i in range(N):
	for j in range(N):
		cnts[(i + j) % 3][cs[i][j] - 1] += 1
ws = [[0] * C for k in range(3)]
for k in range(3):
	for c in range(C):
		ws[k][c] = sum(map(operator.mul, cnts[k], Ds[c]))
ans = float('inf')
for (x, y, z) in itertools.permutations(range(C), 3):
	w = ws[0][x] + ws[1][y] + ws[2][z]
	ans = min(ans, w)
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
from itertools import permutations
colors = tuple((i for i in range(C)))
table = [[0 for i in range(C)] for j in range(3)]
for color in colors:
	for col in range(N):
		for row in range(N):
			table[(col + row) % 3][color] += D[c[col][row] - 1][color]
ans = 10 ** 9
for (i, j, k) in permutations(colors, 3):
	ans = min(ans, table[0][i] + table[1][j] + table[2][k])
print(ans)


def main():
	(N, C) = list(map(int, input().split()))
	D = [None] * C
	for i in range(C):
		D[i] = list(map(int, input().split()))
	c = [None] * N
	for i in range(N):
		c[i] = list(map(int, input().split()))
		c[i] = [x - 1 for x in c[i]]
	STU = [[0] * C, [0] * C, [0] * C]
	for k in range(C):
		for i in range(N):
			for j in range(N):
				STU[(i + j) % 3][k] += D[c[i][j]][k]
	ans = 1000 * N * N
	for i in range(C):
		for j in range(C):
			if j == i:
				continue
			for k in range(C):
				if k == i or k == j:
					continue
				cand = STU[0][i] + STU[1][j] + STU[2][k]
				if cand < ans:
					ans = cand
	return ans
print(main())


from collections import Counter
from itertools import permutations
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
c_field = [list(map(int, input().split())) for i in range(N)]
mod = [[] for _ in range(3)]
for i in range(N):
	for j in range(N):
		mod[(i + j + 2) % 3].append(c_field[i][j])
for i in range(3):
	mod[i] = Counter(mod[i])

def calc(p):
	ret = 0
	for j in range(3):
		for (i, v) in mod[j].items():
			if i == p[j]:
				continue
			ret += D[i - 1][p[j] - 1] * v
	return ret
ans = 10 ** 30
for p in permutations(range(1, C + 1), 3):
	ans = min(ans, calc(p))
print(ans)


(N, C) = map(int, input().split())
(d, c) = ([list(map(int, input().split())) for i in range(C)], [list(map(lambda x: int(x) - 1, input().split())) for i in range(N)])
(cnt, t, ans) = ([[0 for j in range(C)] for i in range(3)], [[0 for j in range(C)] for i in range(3)], float('inf'))
for i in range(N):
	for j in range(N):
		cnt[(i + j) % 3][c[i][j]] += 1
for i in range(3):
	for j in range(C):
		t[i][j] = 0
		for k in range(C):
			t[i][j] += d[k][j] * cnt[i][k]
for i in range(C):
	for j in range(C):
		for k in range(C):
			if i == j or j == k or k == i:
				continue
			ans = min(ans, t[0][i] + t[1][j] + t[2][k])
print(ans)


import itertools
import functools

def inp():
	return list(map(int, input().split()))
(N, C) = inp()
D = [[0] * (C + 1)]
c = [[], [], []]
for i in range(C):
	D.append([0] + inp())
for i in range(N):
	l = inp()
	for j in range(N):
		c[(i + j) % 3].append(l[j])
sc = list(itertools.permutations(list(range(1, C + 1)), 3))
ret = []
for i in range(3):
	ret.append([])
	for j in range(1, C + 1):
		ret[-1].append(sum(list(map(lambda x: D[x][j], c[i]))))
ans = []
for sc_i in sc:
	ans.append(0)
	for i in range(3):
		ans[-1] += ret[i][sc_i[i] - 1]
print(min(ans))


(n, C) = map(int, input().split())
d = [[int(i) for i in input().split()] for _ in range(C)]
c = [[int(i) - 1 for i in input().split()] for _ in range(n)]
cnt0 = [0] * C
cnt1 = [0] * C
cnt2 = [0] * C
for i in range(n):
	for j in range(n):
		for k in range(C):
			if (i + j) % 3 == 0:
				cnt0[k] += d[c[i][j]][k]
			elif (i + j) % 3 == 1:
				cnt1[k] += d[c[i][j]][k]
			else:
				cnt2[k] += d[c[i][j]][k]
ans = float('inf')
for i in range(C):
	for j in range(C):
		if i == j:
			continue
		for k in range(C):
			if i == k or j == k:
				continue
			ans = min(ans, cnt0[i] + cnt1[j] + cnt2[k])
print(ans)


(n, C) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(C)]
c = [[0] * C for _ in range(3)]
for i in range(n):
	for (j, x) in enumerate(map(int, input().split())):
		c[(i + j) % 3][x - 1] += 1
res = 10 ** 10
for i in range(C):
	for j in range(C):
		if i != j:
			for k in range(C):
				if i != k and j != k:
					t = 0
					for l in range(C):
						t += d[l][i] * c[0][l]
					for l in range(C):
						t += d[l][j] * c[1][l]
					for l in range(C):
						t += d[l][k] * c[2][l]
					if t < res:
						res = t
print(res)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
Grid = [list(map(int, input().split())) for _ in range(N)]
SumCost = [[0 for _ in range(C)] for _ in range(3)]
for c in range(1, C + 1):
	for i in range(N):
		for j in range(N):
			g = (i + 1 + (j + 1)) % 3
			SumCost[g][c - 1] += D[Grid[i][j] - 1][c - 1]
ans = 10 ** 18
for c1 in range(1, C + 1):
	for c2 in range(1, C + 1):
		for c3 in range(1, C + 1):
			if c1 == c2 or c2 == c3 or c3 == c1:
				continue
			ans = min(ans, SumCost[0][c1 - 1] + SumCost[1][c2 - 1] + SumCost[2][c3 - 1])
print(ans)


(N, C) = list(map(int, input().split()))
D = [0] * C
for i in range(C):
	D[i] = list(map(int, input().split()))
grid = [0] * N
for i in range(N):
	grid[i] = list(map(int, input().split()))
grid3 = [[0] * C for i in range(3)]
for i in range(N):
	for j in range(N):
		nn = (i + j) % 3
		color = grid[i][j] - 1
		grid3[nn][color] += 1
score = [[0] * C for i in range(3)]
for j in range(C):
	for i in range(3):
		for k in range(C):
			score[i][j] += grid3[i][k] * D[k][j]
ans = 10 ** 10
for i in range(C):
	for j in range(C):
		if i != j:
			for k in range(C):
				if i != k and j != k:
					now = score[0][i] + score[1][j] + score[2][k]
					ans = min(ans, now)
print(ans)


from itertools import permutations
(n, C) = map(int, input().split())
d = [list(map(int, input().split())) for i in range(C)]
c = [list(map(int, input().split())) for i in range(n)]
l = [[0] * C for i in range(3)]
for i in range(n):
	for (j, k) in enumerate(c[i]):
		l[(i + j) % 3][k - 1] += 1
ans = float('inf')
for i in permutations(range(C), 3):
	cnt = 0
	for j in range(3):
		for k in range(C):
			cnt += d[k][i[j]] * l[j][k]
	ans = min(ans, cnt)
print(ans)


(n, d) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(d)]
cost = [[0] * d for _ in range(3)]
c = [list(map(int, input().split())) for _ in range(n)]
for i in range(n):
	for j in range(n):
		cost[(i + j) % 3][c[i][j] - 1] += 1
import itertools
ans = 10 ** 18
s = 0
for p in itertools.permutations(range(1, d + 1), 3):
	for i in range(3):
		for j in range(d):
			s += D[j][p[i] - 1] * cost[i][j]
	if s < ans:
		ans = s
	s = 0
print(ans)


(N, C) = [int(_) for _ in input().split()]
D = [[int(_) for _ in input().split()] for i in range(C)]
c = [[int(_) - 1 for _ in input().split()] for i in range(N)]
from collections import defaultdict
from itertools import permutations
xs = [defaultdict(int) for _ in range(3)]
for (i, row) in enumerate(c):
	for (j, x) in enumerate(row):
		xs[(i + j) % 3][x] += 1
cs = [[sum((D[x][j] * num for (x, num) in xs[i].items())) for j in range(C)] for i in range(3)]
result = min((cs[0][c1] + cs[1][c2] + cs[2][c3] for (c1, c2, c3) in permutations(range(C), 3)))
print(result)


(N, C) = list(map(int, input().split()))
D = [list(map(int, input().split())) for _ in range(C)]
G = [list(map(int, input().split())) for _ in range(N)]
Z = [0] * C
O = [0] * C
T = [0] * C
for x in range(N):
	for y in range(N):
		if (x + y) % 3 == 0:
			Z[G[x][y] - 1] += 1
		elif (x + y) % 3 == 1:
			O[G[x][y] - 1] += 1
		else:
			T[G[x][y] - 1] += 1
ans = 10 ** 9
for c1 in range(C):
	for c2 in range(C):
		for c3 in range(C):
			if c1 == c2 or c2 == c3 or c3 == c1:
				continue
			temp = 0
			for k in range(C):
				temp += Z[k] * D[k][c1]
			for k in range(C):
				temp += O[k] * D[k][c2]
			for k in range(C):
				temp += T[k] * D[k][c3]
			ans = min(ans, temp)
print(ans)


(n, c) = map(int, input().split())
d_s = [list(map(int, input().split())) for _ in range(c)]
c_s = [list(map(int, input().split())) for _ in range(n)]
zot = [[], [], []]
for i in range(n):
	for j in range(n):
		zot[(i + j) % 3].append(c_s[i][j] - 1)
change = [[], [], []]
for i in range(3):
	for j in range(c):
		cnt = 0
		for num in zot[i]:
			cnt += d_s[num][j]
		change[i].append((cnt, j))
	change[i].sort()
ans = 10 ** 10
for (z, i) in change[0][:3]:
	for (o, j) in change[1][:3]:
		if i == j:
			continue
		for (t, k) in change[2][:3]:
			if k == i or k == j:
				continue
			ans = min(ans, z + o + t)
print(ans)


from itertools import *
(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
e = [c * [0] for _ in range(3)]
for i in range(n):
	s = list(map(int, input().split()))
	for j in range(n):
		e[(i + j) % 3][s[j] - 1] += 1
if n == 1:
	print(0)
	exit()
print(min((sum((d[t][i] * e[0][t] + d[t][j] * e[1][t] + d[t][k] * e[2][t] for t in range(c))) for (i, j, k) in permutations((i for i in range(c)), 3))))


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
c = [list(map(int, input().split())) for i in range(N)]
col = [[0] * 3 for i in range(C)]
for i in range(N):
	for j in range(N):
		p = c[i][j] - 1
		for k in range(C):
			col[k][(i + j) % 3] += D[p][k]
ans = 10 ** 18
for i in range(C):
	for j in range(C):
		if i == j:
			continue
		for k in range(C):
			if i == k or j == k:
				continue
			ans = min(ans, col[i][0] + col[j][1] + col[k][2])
print(ans)


import itertools
(N, C) = list(map(int, input().split()))
D = [list(map(int, input().split())) for i in range(C)]
data = [list(map(int, input().split())) for i in range(N)]
s = []
total = [[0 for i in range(C)] for j in range(3)]
ans = []
for i in range(C):
	s.append(i)
col = list(itertools.permutations(s, 3))
for i in range(N):
	for j in range(N):
		total[(i + j + 2) % 3][data[i][j] - 1] += 1
for i in col:
	tempans = 0
	for s in range(3):
		for t in range(C):
			tempans += D[t][i[s]] * total[s][t]
	ans.append(tempans)
print(min(ans))


from itertools import permutations
(N, C) = map(int, input().split())
D = [[int(x) for x in input().split()] for _ in range(C)]
c = [[int(x) for x in input().split()] for _ in range(N)]
n_color = [[0 for _ in range(C)] for _ in range(3)]
for i in range(N):
	for j in range(N):
		X = c[i][j] - 1
		n_color[(i + j + 2) % 3][X] += 1
ans = float('inf')
for paint in permutations(range(C), 3):
	cost = 0
	for ij3 in range(3):
		Y = paint[ij3]
		for X in range(C):
			cost += D[X][Y] * n_color[ij3][X]
	ans = min(ans, cost)
print(ans)


from collections import defaultdict
import itertools
(n, c) = list(map(int, input().split()))
D = [list(map(int, input().split())) for _ in range(c)]
C = [list(map(int, input().split())) for _ in range(n)]
d = [defaultdict(int), defaultdict(int), defaultdict(int)]
for i in range(n):
	for j in range(n):
		r = (i + j) % 3
		d[r][C[i][j]] += 1
cost = [[0] * c for _ in range(3)]
for i in range(3):
	dic = d[i]
	for j in range(c):
		for (k, v) in list(dic.items()):
			cost[i][j - 1] += v * D[k - 1][j - 1]
ans = 1000000000.0
for (i, j, k) in itertools.permutations(list(range(c)), 3):
	ans = min(cost[0][i] + cost[1][j] + cost[2][k], ans)
print(ans)


import sys
input = sys.stdin.readline
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(lambda x: int(x) - 1, input().split())) for N in range(N)]
val = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		for k in range(C):
			val[(i + j) % 3][k] += D[c[i][j]][k]
ans = float('inf')
for i in range(C):
	for j in range(C):
		if i == j:
			continue
		for k in range(C):
			if i == k or j == k:
				continue
			ans = min(ans, val[0][i] + val[1][j] + val[2][k])
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
G = [list(map(int, input().split())) for _ in range(N)]
GC = []
GC.append([0] * C)
GC.append([0] * C)
GC.append([0] * C)
for y in range(N):
	for x in range(N):
		GC[(y + x) % 3][G[y][x] - 1] += 1
ans = 1000000000
for a in range(C):
	for b in range(C):
		if a == b:
			continue
		for c in range(C):
			if a == c or b == c:
				continue
			cost = 0
			for i in range(C):
				cost += GC[0][i] * D[i][a]
				cost += GC[1][i] * D[i][b]
				cost += GC[2][i] * D[i][c]
			ans = min(ans, cost)
print(ans)


from itertools import permutations
(N, C, *L) = map(int, open(0).read().split())
ls = [[0] * (C + 1) for i in range(3)]
D = L[:C * C]
X = L[C * C:]
for i in range(N):
	for j in range(N):
		c = X[i * N + j]
		ls[(i + j) % 3][c] += 1
cost = [[0] * (C + 1) for i in range(3)]
for i in range(3):
	n = sum(ls[i])
	for j in range(1, C + 1):
		for h in range(1, C + 1):
			cost[i][j] += D[(h - 1) * C + j - 1] * ls[i][h]
ans = 10 ** 10
for l in permutations(range(1, C + 1), 3):
	ans = min(ans, sum((cost[i][l[i]] for i in range(3))))
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
G = [list(map(int, input().split())) for i in range(N)]
change = [[0] * C for i in range(3)]
for c in range(C):
	for i in range(1, N + 1):
		for j in range(1, N + 1):
			change[(i + j) % 3][c] += D[G[i - 1][j - 1] - 1][c] if G[i - 1][j - 1] != c + 1 else 0
ans = float('inf')
for c1 in range(C):
	for c2 in range(C):
		for c3 in range(C):
			if len(set((c1, c2, c3))) != 3:
				continue
			ans = min(ans, change[0][c1] + change[1][c2] + change[2][c3])
print(ans)


(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
g0 = [0] * c
g1 = [0] * c
g2 = [0] * c
for i in range(n):
	col = list(map(int, input().split()))
	for j in range(n):
		col[j] -= 1
		if (i + j) % 3 == 0:
			g0[col[j]] += 1
		elif (i + j) % 3 == 1:
			g1[col[j]] += 1
		else:
			g2[col[j]] += 1
ans = 10 ** 18
for i in range(c):
	for j in range(c):
		for k in range(c):
			if i == j or j == k or i == k:
				continue
			s = 0
			for l in range(c):
				s += d[l][i] * g0[l] + d[l][j] * g1[l] + d[l][k] * g2[l]
			ans = min(ans, s)
print(ans)


(n, c) = list(map(int, input().split()))
D_list = [[int(i) for i in input().split()] for _ in range(c)]
c_list = [[int(i) for i in input().split()] for _ in range(n)]
c_num = [[0 for _ in range(3)] for __ in range(c)]
for a in range(n):
	for b in range(n):
		c_num[c_list[b][a] - 1][(a + b + 2) % 3] += 1
ans = 10 ** 10
for i in range(1, c ** 3):
	x = i % c
	y = i % c ** 2 // c
	z = i // c ** 2
	if x == y or y == z or z == x:
		continue
	else:
		color = [x, y, z]
		count = 0
		for s in range(3):
			for t in range(c):
				count += c_num[t][s] * D_list[t][color[s]]
		if count < ans:
			ans = count
print(ans)


import itertools
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
cl_cnt = [[0 for _ in range(C)] for _ in range(3)]
for i in range(N):
	ci = list(map(int, input().split()))
	for (j, cij) in enumerate(ci):
		cl_cnt[(i + j) % 3][cij - 1] += 1
cost = [[0 for _ in range(C)] for _ in range(3)]
for i in range(3):
	for j in range(C):
		for k in range(C):
			cost[i][k] += D[j][k] * cl_cnt[i][j]
ans = 1000 * 500 * 500
for (i, j, k) in itertools.permutations(range(C), 3):
	ans = min(cost[0][i] + cost[1][j] + cost[2][k], ans)
print(ans)


from itertools import product, permutations
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
grid = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]
cost = [[0] * C for _ in range(3)]
for (x, y) in product(range(N), range(N)):
	cost[(x + y) % 3][grid[x][y]] += 1
minn = float('inf')
for colors in permutations(range(C), 3):
	t = 0
	for (s, color_n) in enumerate(colors):
		for (color_p, n) in enumerate(cost[s]):
			t += n * D[color_p][color_n]
	minn = min(minn, t)
print(minn)


from itertools import permutations
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
G = [list(map(int, input().split())) for i in range(N)]
X = [[0] * C for i in range(3)]
for c in range(C):
	tmp = [0] * 3
	for i in range(N):
		for j in range(N):
			tmp[(i + j) % 3] += D[G[i][j] - 1][c]
	for t in range(3):
		X[t][c] = tmp[t]
ans = float('inf')
for (c1, c2, c3) in permutations(range(C), 3):
	ans = min(ans, X[0][c1] + X[1][c2] + X[2][c3])
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
colornum = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		idx = (i + j) % 3
		colornum[idx][c[i][j] - 1] += 1
colors = list(range(C))
import itertools
ans = 10 ** 9 + 7
for v in itertools.permutations(colors, 3):
	val = 0
	for i in range(3):
		x = v[i]
		for j in range(C):
			if x == j:
				continue
			val += colornum[i][j] * D[j][x]
	ans = min(ans, val)
print(ans)


from itertools import permutations
(N, C) = map(int, input().split())
D = []
for _ in range(C):
	line = list(map(int, input().split()))
	D.append(line)
c = []
t = [[0 for _ in range(C)] for _ in range(3)]
for i in range(N):
	line = list(map(int, input().split()))
	for j in range(N):
		r = (i + j) % 3
		t[r][line[j] - 1] += 1
	c.append(line)

def e(conv):
	ret = 0
	for r in range(3):
		for i in range(C):
			ret += t[r][i] * D[i][conv[r] - 1]
	return ret
ret = 10 ** 10
for conv in permutations(range(1, C + 1), 3):
	ret = min(ret, e(conv))
print(ret)


(N, C) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
c_set = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		c_set[(i + j) % 3][c[i][j] - 1] += 1
ans = 1000000000.0
for c_1 in range(C):
	for c_2 in range(C):
		for c_3 in range(C):
			if c_1 == c_2 or c_1 == c_3 or c_2 == c_3:
				continue
			c_list = [c_1, c_2, c_3]
			k = 0
			for i in range(C):
				for j in range(3):
					k += d[i][c_list[j] - 1] * c_set[j][i]
			ans = min(ans, k)
print(ans)


(N, C) = map(int, input().split())
d = []
c = []
t = [[0] * C, [0] * C, [0] * C]
for _ in range(C):
	d.append(list(map(int, input().split())))
for _ in range(N):
	c.append(list(map(int, input().split())))
for i in range(N):
	for j in range(N):
		t[(i + j) % 3][c[i][j] - 1] += 1
ans = 1000 * N * N
for i in range(C):
	for j in range(C):
		if i != j:
			for k in range(C):
				if i != k and j != k:
					tt = 0
					for l in range(C):
						tt += d[l][i] * t[0][l] + d[l][j] * t[1][l] + d[l][k] * t[2][l]
					ans = min(ans, tt)
print(ans)


(n, c) = map(int, input().split())
lis = [list(map(int, input().split())) for i in range(c)]
li = [list(map(int, input().split())) for i in range(n)]
ans = 10 ** 100
cnt = [0, 0, 0]
masu = [[0 for i in range(c)] for j in range(3)]
for i in range(n):
	for j in range(n):
		cnt[(i + j) % 3] += 1
		masu[(i + j) % 3][li[i][j] - 1] += 1
for i in range(c):
	for j in range(c):
		if i != j:
			for k in range(c):
				if i != k and j != k:
					tryans = 0
					num = [i, j, k]
					for l in range(3):
						for h in range(c):
							if h != num[l]:
								tryans += lis[h][num[l]] * masu[l][h]
					ans = min(ans, tryans)
print(ans)


(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for i in range(c)]
lis_c = [list(map(int, input().split())) for i in range(n)]
ans = float('inf')
cnt = [[0] * c for i in range(3)]
for i in range(n):
	for j in range(n):
		cnt[(i + j) % 3][lis_c[i][j] - 1] += 1
for i in range(c):
	for j in range(c):
		for k in range(c):
			if i == j or j == k or i == k:
				continue
			tmp = 0
			color = [i, j, k]
			for l in range(3):
				for m in range(c):
					tmp += cnt[l][m] * d[m][color[l % 3]]
			ans = min(ans, tmp)
print(ans)


(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
cc = [list(map(int, input().split())) for _ in range(n)]
ans = 10 ** 15
cnt = [[0] * c for _ in range(3)]
for i in range(n):
	for j in range(n):
		cnt[(i + j) % 3][cc[i][j] - 1] += 1
for i in range(c):
	for j in range(c):
		for k in range(c):
			pre_ans = 0
			if i == j or j == k or k == i:
				continue
			for l in range(3):
				for m in range(c):
					if l % 3 == 0 and m != i:
						pre_ans += cnt[l][m] * d[m][i]
					elif l % 3 == 1 and m != j:
						pre_ans += cnt[l][m] * d[m][j]
					elif l % 3 == 2 and m != k:
						pre_ans += cnt[l][m] * d[m][k]
			ans = min(ans, pre_ans)
print(ans)


from itertools import permutations

def main():
	(N, C) = map(int, input().split())
	Dc = [tuple(map(int, input().split())) for _ in [0] * C]
	Cn = [tuple(map(int, input().split())) for _ in [0] * N]
	sum_ = [[0] * C for _ in [0] * 3]
	for (i, cn) in enumerate(Cn):
		for (j, c) in enumerate(cn):
			n = (i + j) % 3
			for k in range(C):
				sum_[n][k] += Dc[c - 1][k]
	cost = float('inf')
	for (i, j, k) in permutations(range(C), 3):
		cost = min(cost, sum_[0][i] + sum_[1][j] + sum_[2][k])
	print(cost)
main()


from itertools import permutations
(n, n_color) = map(int, input().split())
change_cost = [list(map(int, input().split())) for i in range(n_color)]
color_grid = [list(map(int, input().split())) for i in range(n)]
mod0_colors = [0] * n_color
mod1_colors = [0] * n_color
mod2_colors = [0] * n_color
for y in range(n):
	for x in range(n):
		color = color_grid[y][x] - 1
		if (y + x + 2) % 3 == 0:
			mod0_colors[color] += 1
		elif (y + x + 2) % 3 == 1:
			mod1_colors[color] += 1
		else:
			mod2_colors[color] += 1
mod2color_cost = [[0] * n_color for _ in range(3)]
for (mod, mod_colors) in enumerate([mod0_colors, mod1_colors, mod2_colors]):
	for color_to in range(n_color):
		total_cost = 0
		for color_from in range(n_color):
			cost_per_node = change_cost[color_from][color_to]
			n_node = mod_colors[color_from]
			total_cost += n_node * cost_per_node
		mod2color_cost[mod][color_to] = total_cost
ans = float('inf')
for pettern in permutations([i for i in range(n_color)], 3):
	total_cost = 0
	for from_ in range(3):
		to = pettern[from_]
		total_cost += mod2color_cost[from_][to]
	ans = min(ans, total_cost)
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
c = [list(map(int, input().split())) for i in range(N)]
d = [[0 for j in range(C)] for i in range(3)]
for i in range(N):
	for j in range(N):
		m = (i + j) % 3
		cc = c[i][j] - 1
		for k in range(C):
			d[m][k] += D[cc][k]
res = 2 * 10 ** 9
for i in range(C):
	for j in range(C):
		if i == j:
			continue
		for k in range(C):
			if k in (i, j):
				continue
			res = min(res, d[0][i] + d[1][j] + d[2][k])
else:
	print(res)


from itertools import permutations
(N, C) = list(map(int, input().split()))
D = [list(map(int, input().split())) for i in range(C)]
colors = [[0] * C for i in range(3)]
for i in range(N):
	tmp = list(map(int, input().split()))
	for (j, color) in enumerate(tmp):
		num = (i + 1 + (j + 1)) % 3
		colors[num][color - 1] += 1
data = [[0] * C for i in range(3)]
for i in range(3):
	for j in range(C):
		for k in range(C):
			data[i][k] += colors[i][j] * D[j][k]
ans = 10 ** 10
for iter_ in permutations(list(range(C)), 3):
	tmp = []
	for (i, j) in enumerate(iter_):
		tmp.append(data[i][j])
	ans = min(ans, sum(tmp))
print(ans)


from collections import defaultdict
(N, C) = list(map(int, input().split()))
D = [tuple(map(int, input().split())) for _ in range(C)]
grid = [tuple(map(int, input().split())) for _ in range(N)]
mod_0 = defaultdict(int)
mod_1 = defaultdict(int)
mod_2 = defaultdict(int)
for i in range(N):
	for j in range(N):
		if (i + 1 + j + 1) % 3 == 0:
			mod_0[grid[i][j]] += 1
		elif (i + 1 + j + 1) % 3 == 1:
			mod_1[grid[i][j]] += 1
		elif (i + 1 + j + 1) % 3 == 2:
			mod_2[grid[i][j]] += 1
ans = float('inf')
for i in range(C):
	for j in range(C):
		if i == j:
			continue
		for k in range(C):
			if k in [i, j]:
				continue
			total = 0
			for (prev, cnt) in list(mod_0.items()):
				total += D[prev - 1][i] * cnt
			for (prev, cnt) in list(mod_1.items()):
				total += D[prev - 1][j] * cnt
			for (prev, cnt) in list(mod_2.items()):
				total += D[prev - 1][k] * cnt
			ans = min(ans, total)
print(ans)


(n, c) = map(int, input().split())
D = [[0] * c for i in range(c)]
for i in range(c):
	D[i] = list(map(int, input().split()))
C = [[0] * n for i in range(n)]
for i in range(n):
	C[i] = list(map(int, input().split()))
	for j in range(n):
		C[i][j] = C[i][j] - 1
A = [[0] * c for i in range(3)]
for i in range(n):
	for j in range(n):
		A[(i + j) % 3][C[i][j]] += 1
ans = 0
e = 10 ** 20
for i in range(c):
	for j in range(c):
		if j == i:
			continue
		for k in range(c):
			if k == i:
				continue
			if k == j:
				continue
			f = 0
			for u in range(c):
				f = f + A[0][u] * D[u][i] + A[1][u] * D[u][j] + A[2][u] * D[u][k]
			if e > f:
				e = f
print(e)


import itertools
(N, C) = map(int, input().split())
D = [[int(a) for a in input().split()] for i in range(C)]
X = [[int(a) - 1 for a in input().split()] for i in range(N)]
T = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		T[(i + j) % 3][X[i][j]] += 1
P = [[0] * C for _ in range(3)]
for i in range(3):
	for j in range(C):
		P[i][j] = sum([D[k][j] * T[i][k] for k in range(C)])
ans = 1 << 100
for (a, b, c) in itertools.permutations(range(C), 3):
	ans = min(ans, P[0][a] + P[1][b] + P[2][c])
print(ans)


import itertools

def calc(colo, target, d_mtx):
	ret = 0
	for (i, item) in enumerate(colo):
		ret += item * d_mtx[i][target]
	return ret
(n, c) = list(map(int, input().split()))
d_mtx = []
c_mtx = []
for i in range(c):
	d_mtx.append(list(map(int, input().split())))
for i in range(n):
	c_mtx.append(list(map(int, input().split())))
color = [[0] * c for _ in range(3)]
for i in range(n):
	for j in range(n):
		color[(i + 1 + (j + 1)) % 3][c_mtx[i][j] - 1] += 1
ret = 10 ** 10
for item in itertools.permutations(list(range(c)), 3):
	tmp = 0
	for i in range(3):
		tmp += calc(color[i], item[i], d_mtx)
	ret = min(ret, tmp)
print(ret)


from itertools import permutations
import sys
input = sys.stdin.readline
(N, C) = map(int, input().split())
D = [tuple(map(int, input().split())) for _ in [0] * C]
K = [tuple(map(int, input().split())) for _ in [0] * N]
T = [[0] * C for _ in [0] * 3]
for (i, _k) in enumerate(K):
	for (j, k) in enumerate(_k):
		z = (i + j) % 3
		T[z][k - 1] += 1
ans = float('inf')
for (a, b, c) in permutations(range(C), 3):
	cost = 0
	cost += sum((t * D[i][a] for (i, t) in enumerate(T[0])))
	cost += sum((t * D[i][b] for (i, t) in enumerate(T[1])))
	cost += sum((t * D[i][c] for (i, t) in enumerate(T[2])))
	ans = min(ans, cost)
print(ans)


(n, c) = (int(i) for i in input().split())
d = [[int(i) for i in input().split()] for i in range(c)]
x = [[int(i) for i in input().split()] for i in range(n)]
(lis0, lis1, lis2) = ([0 for i in range(c)], [0 for i in range(c)], [0 for i in range(c)])
for i in range(n):
	for j in range(n):
		if (i + j) % 3 == 0:
			lis2[x[i][j] - 1] += 1
		elif (i + j) % 3 == 1:
			lis0[x[i][j] - 1] += 1
		else:
			lis1[x[i][j] - 1] += 1
from itertools import permutations
(y, ans) = ([i for i in range(c)], float('inf'))
for (i, j, k) in list(permutations(y, 3)):
	num = 0
	for i2 in range(c):
		num += lis0[i2] * d[i2][i] + lis1[i2] * d[i2][j] + lis2[i2] * d[i2][k]
	ans = min(ans, num)
print(ans)


3
from itertools import combinations, permutations

def main():
	(n, nc) = list(map(int, input().split()))
	md = [list(map(int, input().split())) for _ in range(nc)]
	mc = [list([int(c) - 1 for c in input().split()]) for _ in range(n)]
	cnt_c = [[0] * nc for _ in range(3)]
	for i in range(n):
		for j in range(n):
			cnt_c[(i + j) % 3][mc[i][j]] += 1

	def calc_cost(lx, itarget):
		return sum([cnt * md[i][itarget] for (i, cnt) in enumerate(lx)])
	cost = 10 ** 9
	for inds in combinations(list(range(nc)), 3):
		for itargets in permutations(inds):
			cost = min(cost, sum([calc_cost(cnt_c[i], itarget) for (i, itarget) in enumerate(itargets)]))
	print(cost)

def __starting_point():
	main()
__starting_point()


from itertools import product, permutations
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]
res = 1000 * N * N
cnt = [[0] * C for _ in range(3)]
for (i, j) in product(range(N), range(N)):
	cnt[(i + j) % 3][c[i][j]] += 1
for (c1, c2, c3) in permutations(range(C), 3):
	score = 0
	for (cc, cn) in enumerate(cnt[0]):
		score += cn * D[cc][c1]
	for (cc, cn) in enumerate(cnt[1]):
		score += cn * D[cc][c2]
	for (cc, cn) in enumerate(cnt[2]):
		score += cn * D[cc][c3]
	if res > score:
		res = score
print(res)


from itertools import permutations
(N, C) = map(int, input().split())
(D, P) = ([], [[0] * C for _ in range(3)])
for i in range(C):
	D.append(list(map(int, input().split())))
for i in range(N):
	for (j, c) in enumerate(map(int, input().split())):
		P[(i + j) % 3][c - 1] += 1
res = float('inf')
for q in permutations(range(C), 3):
	tmp = 0
	for k in range(3):
		c = q[k]
		for (i, p) in enumerate(P[k]):
			tmp += D[i][c] * p
	res = min(tmp, res)
print(res)


import sys
input = sys.stdin.readline
(N, M) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(M)]
C = [list(map(int, input().split())) for _ in range(N)]
X = [[0 for _ in range(M)] for _ in range(3)]
for i in range(N):
	for j in range(N):
		x = (i + 1 + j + 1) % 3
		y = C[i][j] - 1
		X[x][y] += 1
Y = [[0 for _ in range(M)] for _ in range(3)]
for i in range(3):
	for c_to in range(M):
		total = 0
		for c_from in range(M):
			total += X[i][c_from] * D[c_from][c_to]
		Y[i][c_to] = total
ans = 10 ** 10
for i in range(M):
	for j in range(M):
		for k in range(M):
			if i != j and j != k and (k != i):
				ans = min(ans, Y[0][i] + Y[1][j] + Y[2][k])
print(ans)


import itertools
(N, C) = map(int, input().split())
D = [0] + [[0] + list(map(int, input().split())) for i in range(C)]
c = [list(map(int, input().split())) for i in range(N)]
grids = [[], [], []]
for i in range(N):
	for j in range(N):
		grids[(i + j) % 3].append(c[i][j])
iwa = [[0] * (C + 1) for i in range(3)]
for i in range(3):
	for j in range(1, C + 1, 1):
		for k in range(len(grids[i])):
			iwa[i][j] += D[grids[i][k]][j]
ans = float('inf')
for bits in itertools.permutations(list(range(1, C + 1)), 3):
	tmpans = 0
	for i in range(3):
		tmpans += iwa[i][bits[i]]
	ans = min(tmpans, ans)
print(ans)


(N, C) = map(int, input().split())
data = [list(map(int, input().split())) for _ in range(C)]
color = [[0] * C for _ in range(3)]
for i in range(N):
	c = input().split()
	for j in range(N):
		color[(i + j) % 3][int(c[j]) - 1] += 1
sumcolor = [[0] * C for _ in range(3)]
for i in range(3):
	for j in range(C):
		for c in range(C):
			sumcolor[i][j] += color[i][c] * data[c][j]
answer = 10 ** 18
for i in range(C):
	for j in range(C):
		for k in range(C):
			if i != j and i != k and (j != k):
				answer = min(answer, sumcolor[0][i] + sumcolor[1][j] + sumcolor[2][k])
print(answer)


from collections import defaultdict
(n, c) = map(int, input().split())
x = [list(map(int, input().split())) for i in range(c)]
e = [[0] * c for i in range(3)]
for i in range(n):
	a = list(map(int, input().split()))
	for j in range(n):
		e[(i + j + 2) % 3][a[j] - 1] += 1
p = float('inf')
for i in range(c):
	for j in range(c):
		if i != j:
			for h in range(c):
				if i != h and j != h:
					p = min(p, sum([x[s][i] * d for (s, d) in enumerate(e[0])] + [x[s][j] * d for (s, d) in enumerate(e[1])] + [x[s][h] * d for (s, d) in enumerate(e[2])]))
print(p)


(N, C) = map(int, input().split())
Dmat = []
for i in range(C):
	array = list(map(int, input().split()))
	Dmat.append(array)
grid_list = [{}, {}, {}]
for i in range(N):
	array = list(map(int, input().split()))
	for j in range(N):
		c = array[j] - 1
		mod = (i + j) % 3
		if c in grid_list[mod]:
			grid_list[mod][c] += 1
		else:
			grid_list[mod][c] = 1
min_cost = 10 ** 9
for i in range(C):
	for j in range(C):
		if i == j:
			continue
		for k in range(C):
			if i == k or j == k:
				continue
			cost = 0
			for (c, num) in grid_list[0].items():
				cost += Dmat[c][i] * num
			for (c, num) in grid_list[1].items():
				cost += Dmat[c][j] * num
			for (c, num) in grid_list[2].items():
				cost += Dmat[c][k] * num
			if cost < min_cost:
				min_cost = cost
print(min_cost)


from itertools import permutations

def main():
	(n, c) = list(map(int, input().split()))
	d = [[int(x) for x in input().split()] for _ in range(c)]
	g = [[int(x) - 1 for x in input().split()] for _ in range(n)]
	count = [{}, {}, {}]
	for i in range(n):
		for j in range(n):
			now = g[i][j]
			index = (i + j + 2) % 3
			if now in count[index % 3]:
				count[index % 3][now] += 1
			else:
				count[index % 3][now] = 1
	answer = float('inf')
	for color in permutations([i for i in range(c)], 3):
		now_answer = 0
		for i in range(3):
			for (before_color, num) in list(count[i].items()):
				now_answer += d[before_color][color[i]] * num
		answer = min(answer, now_answer)
	print(answer)

def __starting_point():
	main()
__starting_point()


(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
a = [[0] * c for _ in range(3)]
b = [[[0, i] for i in range(c)] for _ in range(3)]
for i in range(n):
	l = list(map(int, input().split()))
	for j in range(n):
		a[(i + j) % 3][l[j] - 1] += 1
for i in range(3):
	for k in range(c):
		b[i][k][0] = sum([a[i][t] * d[t][k] for t in range(c)])
p = [[], [], []]
for i in range(3):
	p[i] = sorted(b[i])[:3]
m = []
for t in p[0]:
	for s in p[1]:
		for u in p[2]:
			if t[1] != s[1] and t[1] != u[1] and (s[1] != u[1]):
				m.append(t[0] + s[0] + u[0])
print(min(m))


import sys, queue, math, copy, itertools, bisect, collections, heapq
INF = 10 ** 18
LI = lambda : [int(x) for x in sys.stdin.readline().split()]
(N, C) = LI()
D = [LI() for _ in range(C)]
p = [LI() for _ in range(N)]
q = [[0] * (C + 1) for _ in range(3)]
for i in range(N):
	for j in range(N):
		k = (i + j) % 3
		q[k][p[i][j]] += 1
ans = INF
for col in itertools.permutations(range(1, C + 1), 3):
	iwa = 0
	for i in range(3):
		for j in range(1, C + 1):
			iwa += D[j - 1][col[i] - 1] * q[i][j]
	ans = min(ans, iwa)
print(ans)


from collections import defaultdict
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
strange = [defaultdict(lambda : 0) for _ in range(3)]
for i in range(N):
	for j in range(N):
		for color in range(C):
			strange[(i + j) % 3][color] += D[c[i][j] - 1][color]
ans = 1000 * N ** 2
for c1 in range(C):
	for c2 in range(C):
		for c3 in range(C):
			if c1 != c2 and c2 != c3 and (c3 != c1):
				ans = min(ans, strange[0][c1] + strange[1][c2] + strange[2][c3])
print(ans)


(N, C) = map(int, input().split())
D = []
for _ in range(C):
	D.append(list(map(int, input().split())))
c = []
for _ in range(N):
	c.append(list(map(int, input().split())))
colors = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		colors[(i + j) % 3][c[i][j] - 1] += 1
ans = 10 ** 10
for i in range(C):
	for j in range(C):
		if i == j:
			continue
		for k in range(C):
			if j == k or k == i:
				continue
			tmp = 0
			for l in range(C):
				tmp += colors[0][l] * D[l][i]
				tmp += colors[1][l] * D[l][j]
				tmp += colors[2][l] * D[l][k]
			ans = min(ans, tmp)
print(ans)


import itertools
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
grid = [list(map(int, input().split())) for _ in range(N)]
ans = 10 ** 10
group = {g: {c: 0 for c in range(C)} for g in range(3)}
for (i, row) in enumerate(grid):
	for (j, r) in enumerate(row):
		group[(i + j) % 3][r - 1] += 1
for tup in itertools.combinations(range(C), 3):
	for (c1, c2, c3) in itertools.permutations(tup):
		temp = 0
		for c in range(C):
			for (g, col) in zip(range(3), [c1, c2, c3]):
				temp += group[g][c] * D[c][col]
		if ans > temp:
			ans = temp
print(ans)


(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for i in range(c)]
s = [list(map(int, input().split())) for i in range(n)]
x = [0] * c
y = [0] * c
z = [0] * c
for i in range(n):
	for j in range(n):
		a = (i + j) % 3
		if a == 0:
			x[s[i][j] - 1] += 1
		if a == 1:
			y[s[i][j] - 1] += 1
		if a == 2:
			z[s[i][j] - 1] += 1
ans = 10 ** 16
for i in range(c):
	for j in range(c):
		for k in range(c):
			if i != j and i != k and (j != k):
				o = 0
				for l in range(c):
					o += d[l][i] * x[l]
				p = 0
				for l in range(c):
					p += d[l][j] * y[l]
				q = 0
				for l in range(c):
					q += d[l][k] * z[l]
				ans = min(ans, o + p + q)
print(ans)


from itertools import permutations

def main():
	(N, C) = map(int, input().split())
	D = list((list(map(int, input().split())) for _ in range(C)))
	c = list((list(map(int, input().split())) for _ in range(N)))
	cost = [[0] * (C + 5) for _ in range(3)]
	for k in range(C):
		for i in range(N):
			for j in range(N):
				cost[(i + j) % 3][k + 1] += D[c[i][j] - 1][k]
	ans = float('inf')
	for (a, b, c) in permutations(range(1, C + 1), 3):
		tmp = cost[0][a] + cost[1][b] + cost[2][c]
		ans = min(tmp, ans)
	print(ans)
main()


(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for i in range(c)]
l = [list(map(int, input().split())) for i in range(n)]
ll = [[0] * c for i in range(3)]
for i in range(n):
	for j in range(n):
		x = (i + j + 2) % 3
		ll[x][l[i][j] - 1] += 1
ans = float('INF')
for i in range(c):
	for j in range(c):
		if i == j:
			continue
		for k in range(c):
			if i == k or j == k:
				continue
			count = 0
			ch = [i, j, k]
			for m in range(3):
				for t in range(c):
					count += ll[m][t] * d[t][ch[m]]
			ans = min(ans, count)
print(ans)


from itertools import permutations
import sys
input = sys.stdin.readline
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]
count = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		count[(i + j) % 3][c[i][j]] += 1
ans = float('inf')
for p in permutations(range(C), 3):
	tmp = 0
	for i in range(3):
		for j in range(C):
			tmp += count[i][j] * D[j][p[i]]
	ans = min(ans, tmp)
print(ans)


from itertools import permutations
(n, c) = map(int, input().split())
d_lst = [list(map(int, input().split())) for _ in range(c)]
c_lst = [list(map(int, input().split())) for _ in range(n)]
lst = [[0] * c for _ in range(3)]
for i in range(n):
	for j in range(n):
		lst[(i + j) % 3][c_lst[i][j] - 1] += 1
cnt = []
for i in range(c):
	temp = []
	for j in range(3):
		cal = 0
		for k in range(c):
			cal += lst[j][k] * d_lst[k][i]
		temp.append(cal)
	cnt.append(temp)
temp = []
for l in permutations(list(range(c)), 3):
	temp.append(cnt[l[0]][0] + cnt[l[1]][1] + cnt[l[2]][2])
print(min(temp))


from itertools import permutations
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
grid = [list(map(int, input().split())) for _ in range(N)]
cnt = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		cnt[(i + j) % 3][grid[i][j] - 1] += 1
ans = N * N * 1000 + 10
for color in permutations(range(C), 3):
	dis = 0
	for i in range(3):
		for j in range(C):
			d = D[j][color[i]]
			num = cnt[i][j]
			dis += d * num
	ans = min(ans, dis)
print(ans)


from itertools import product
from collections import Counter
(N, C) = map(int, input().split())
D = [tuple(map(int, input().split())) for _ in range(C)]
color = [[] for _ in range(3)]
for i in range(N):
	inp = tuple(map(int, input().split()))
	for (j, c) in enumerate(inp):
		color[(i + j) % 3].append(c - 1)
cnt = [Counter(color[i]) for i in range(3)]

def point(d, col):
	res = 0
	for (k, v) in d.items():
		res += D[k][col] * v
	return res
ans = 10 ** 9
for xyz in product(range(C), repeat=3):
	if len(set(xyz)) != 3:
		continue
	tmp = sum((point(cnt[i], xyz[i]) for i in range(3)))
	ans = min(ans, tmp)
print(ans)


from sys import stdin
import numpy as np

def main():
	readline = stdin.readline
	(n, max_c) = map(int, readline().split())
	d = [list(map(int, readline().split())) for _ in range(max_c)]
	d = np.array(d, dtype=np.int64)
	c = [list(map(lambda x: int(x) - 1, readline().split())) for _ in range(n)]
	color_table = np.zeros((3, max_c), dtype=np.int64)
	for i in range(n):
		for j in range(n):
			color_table[(i + j + 2) % 3, :] += d[c[i][j], :]
	ans = float('inf')
	for i in range(max_c):
		for j in range(max_c):
			for k in range(max_c):
				if i == j or j == k or k == i:
					continue
				ans = min(ans, color_table[0][i] + color_table[1][j] + color_table[2][k])
	print(ans)

def __starting_point():
	main()
__starting_point()


import itertools
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
c = [list(map(int, input().split())) for i in range(N)]
indices = [2, 0, 1]
count_color = [[0] * C for i in range(3)]
for i in range(N):
	idx = indices[i % 3]
	for j in range(N):
		count_color[idx][c[i][j] - 1] += 1
		idx = (idx + 1) % 3
ans = float('inf')
correspondence = list(itertools.permutations(range(C), 3))
for corr in correspondence:
	cost = 0
	for idx in range(3):
		for color in range(C):
			cost += count_color[idx][color] * D[color][corr[idx]]
	ans = min(ans, cost)
print(ans)


(n, c) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(c)]
C = [list(map(int, input().split())) for _ in range(n)]
for (i, l) in enumerate(C):
	l = [x - 1 for x in l]
	C[i] = l
import itertools
ans = 10 ** 18
X = [[0] * 3 for _ in range(c)]
for i in range(n):
	for j in range(n):
		x = C[i][j]
		X[x][(i + j) % 3] += 1
for p in itertools.permutations(range(c), 3):
	temp = 0
	for i in range(3):
		for j in range(c):
			temp += X[j][i] * D[j][p[i]]
	ans = min(temp, ans)
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in [0] * C]
c = [list(map(int, input().split())) for _ in [0] * N]
t = [[0] * C for _ in [0] * 3]
for i in range(N):
	for j in range(N):
		t[(i + j) % 3][c[i][j] - 1] += 1
s = float('inf')
for i in range(C):
	for j in range(C):
		if j == i:
			continue
		for k in range(C):
			if k == i or k == j:
				continue
			s = min(s, sum((t[0][n] * D[n][i] for n in range(C))) + sum((t[1][n] * D[n][j] for n in range(C))) + sum((t[2][n] * D[n][k] for n in range(C))))
print(s)


import sys
import math
import collections
import bisect
import copy
import itertools
sys.setrecursionlimit(10 ** 7)
INF = 10 ** 16
MOD = 10 ** 9 + 7
ni = lambda : int(sys.stdin.readline())
ns = lambda : list(map(int, sys.stdin.readline().split()))
na = lambda : list(map(int, sys.stdin.readline().split()))
na1 = lambda : list([int(x) - 1 for x in sys.stdin.readline().split()])

def main():
	(n, c) = ns()
	d = [na() for _ in range(c)]
	color = [na() for _ in range(n)]
	cnt = [[0] * c for _ in range(3)]
	for i in range(n):
		for j in range(n):
			cnt[(i + j) % 3][color[i][j] - 1] += 1
	ans = INF
	for cost in itertools.permutations(list(range(c)), 3):
		tmp_ans = 0
		for i in range(3):
			for j in range(c):
				tmp_ans += cnt[i][j] * d[j][cost[i]]
		ans = min(ans, tmp_ans)
	print(ans)

def __starting_point():
	main()
__starting_point()


import sys
from itertools import permutations
(N, C) = map(int, input().split())
D = [list(map(int, sys.stdin.readline().split())) for _ in range(C)]
CM = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
CG = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		nc = CM[i][j] - 1
		for c in range(C):
			CG[(i + j) % 3][c] += D[nc][c]
ans = 10 ** 10
for (c1, c2, c3) in permutations(range(C), 3):
	ans = min(ans, CG[0][c1] + CG[1][c2] + CG[2][c3])
print(ans)


import sys
input = sys.stdin.readline
from itertools import permutations

def main():
	(N, C) = map(int, input().split())
	D = [list(map(int, input().split())) for _ in range(C)]
	grid = [list(map(int, input().split())) for _ in range(N)]
	sup0 = [0] * C
	sup1 = [0] * C
	sup2 = [0] * C
	for i in range(N):
		for j in range(N):
			if (i + j) % 3 == 0:
				sup2[grid[i][j] - 1] += 1
			elif (i + j) % 3 == 1:
				sup0[grid[i][j] - 1] += 1
			elif (i + j) % 3 == 2:
				sup1[grid[i][j] - 1] += 1
	ans = 10 ** 18
	for (i, j, k) in permutations(range(C), 3):
		tmp = 0
		for c in range(C):
			tmp += D[c][i] * sup0[c]
			tmp += D[c][j] * sup1[c]
			tmp += D[c][k] * sup2[c]
		ans = min(ans, tmp)
	print(ans)

def __starting_point():
	main()
__starting_point()


import itertools
(N, C) = map(int, input().split())
D = [0] + [[0] + list(map(int, input().split())) for i in range(C)]
c = [list(map(int, input().split())) for i in range(N)]
grid = [[], [], []]
for i in range(N):
	for j in range(N):
		grid[(i + j) % 3].append(c[i][j])
s = [[0] * (C + 1) for i in range(3)]
for i in range(3):
	for j in range(1, C + 1, 1):
		for k in range(len(grid[i])):
			s[i][j] += D[grid[i][k]][j]
ans = float('inf')
for p in itertools.permutations(list(range(1, C + 1)), 3):
	tmp = 0
	for i in range(3):
		tmp += s[i][p[i]]
	ans = min(tmp, ans)
print(ans)


from itertools import *
(n, c) = map(int, input().split())
cost = [list(map(int, input().split())) for i in range(c)]
d = [[0] * c for i in range(3)]
for i in range(n):
	for (j, v) in enumerate(map(int, input().split())):
		d[(i + j) % 3][v - 1] += 1
print(min((sum((cost[j][cmb[i]] * d[i][j] for j in range(c) for i in range(3))) for cmb in permutations(range(c), 3))))


(N, C) = map(int, input().split())
D = [[int(i) for i in input().split()] for _ in range(C)]
c = [[int(i) for i in input().split()] for _ in range(N)]
modl = [[0 for i in range(C)] for i in range(3)]
for i in range(N):
	for j in range(N):
		modl[(i + 1 + (j + 1)) % 3][c[i][j] - 1] += 1
ans = float('inf')
for i in range(C):
	for j in range(C):
		for k in range(C):
			if i == j or i == k or j == k:
				continue
			total = 0
			for l in range(C):
				total += D[l][i] * modl[0][l] + D[l][j] * modl[1][l] + D[l][k] * modl[2][l]
			ans = min(ans, total)
print(ans)


(N, C) = map(int, input().split())
D = []
for i in range(C):
	D.append(list(map(int, input().split())))
cc = [[0] * C for i in range(3)]
for i in range(N):
	color = list(map(int, input().split()))
	for j in range(len(color)):
		cc[(i + j) % 3][color[j] - 1] += 1
iwakan = [[[0, 0] for _ in range(C)] for _ in range(3)]
for i in range(3):
	for j in range(C):
		tmp = 0
		for k in range(len(cc[i])):
			tmp += cc[i][k] * D[k][j]
		iwakan[i][j][0] = tmp
		iwakan[i][j][1] = j
ans = 10 ** 15
for i in range(len(iwakan)):
	iwakan[i] = sorted(iwakan[i], key=lambda x: x[0])
for i in range(3):
	for j in range(3):
		if iwakan[0][i][1] == iwakan[1][j][1]:
			continue
		for k in range(3):
			if iwakan[0][i][1] == iwakan[2][k][1]:
				continue
			if iwakan[1][j][1] == iwakan[2][k][1]:
				continue
			ans = min(ans, iwakan[0][i][0] + iwakan[1][j][0] + iwakan[2][k][0])
print(ans)


from itertools import permutations
(N, C) = map(int, input().split())
D = []
for c in range(C):
	D.append(list(map(int, input().split())))
c = []
for i in range(N):
	c.append(list(map(lambda x: int(x) - 1, input().split())))
color = [[0] * C for i in range(3)]
cost = [[0] * C for i in range(3)]
for i in range(N):
	for j in range(N):
		mod = (i + j + 2) % 3
		oldc = c[i][j]
		for (ci, cl) in enumerate(D[oldc]):
			cost[mod][ci] += cl
mnc = float('inf')
for (i, j, k) in permutations(range(C), 3):
	cst = cost[0][i] + cost[1][j] + cost[2][k]
	if cst < mnc:
		mnc = cst
print(mnc)


from collections import Counter
from itertools import permutations
(n, c) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
a = [[] for _ in range(3)]
for i in range(n):
	for (j, x) in enumerate(map(lambda x: int(x) - 1, input().split())):
		a[(i + j) % 3].append(x)
cnt = list(map(lambda x: Counter(x), a))
ans = float('inf')
for cp in permutations(range(c), 3):
	res = 0
	for (i, x) in enumerate(cp):
		for px in cnt[i].keys():
			res += d[px][x] * cnt[i][px]
	ans = min(res, ans)
print(ans)


from collections import defaultdict
import itertools
(n, c) = list(map(int, input().split()))
D = [list(map(int, input().split())) for _ in range(c)]
diago0 = defaultdict(int)
diago1 = defaultdict(int)
diago2 = defaultdict(int)
for i in range(n):
	for (j, color) in enumerate(map(int, input().split())):
		color -= 1
		if (i + j) % 3 == 0:
			diago0[color] += 1
		elif (i + j) % 3 == 1:
			diago1[color] += 1
		else:
			diago2[color] += 1
cost0 = [0] * c
cost1 = [0] * c
cost2 = [0] * c
for i in range(c):
	for (k, v) in list(diago0.items()):
		cost0[i] += D[k][i] * v
for i in range(c):
	for (k, v) in list(diago1.items()):
		cost1[i] += D[k][i] * v
for i in range(c):
	for (k, v) in list(diago2.items()):
		cost2[i] += D[k][i] * v
INF = 10 ** 18
ans = INF
for trio in itertools.combinations(list(range(c)), 3):
	for (a, b, c) in itertools.permutations(trio, 3):
		cost = cost0[a] + cost1[b] + cost2[c]
		if cost < ans:
			ans = cost
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
C0 = [0] * C
C1 = [0] * C
C2 = [0] * C
for i in range(N):
	for j in range(N):
		if (i + j) % 3 == 0:
			C0[c[i][j] - 1] += 1
		elif (i + j) % 3 == 1:
			C1[c[i][j] - 1] += 1
		else:
			C2[c[i][j] - 1] += 1
import itertools
A = list(itertools.permutations(range(1, C + 1), 3))
ans = 1000 * 250000
for (a, b, c) in A:
	d = 0
	for i in range(C):
		d += C0[i] * D[i][a - 1]
		d += C1[i] * D[i][b - 1]
		d += C2[i] * D[i][c - 1]
	ans = min(ans, d)
print(ans)


from itertools import *
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in [0] * C]
c = [list(map(int, input().split())) for _ in [0] * N]
tri = [[] for _ in [0] * 3]
for i in range(1, N + 1):
	for j in range(1, N + 1):
		tri[(i + j) % 3] += [c[i - 1][j - 1] - 1]
incom = [[0] * C for _ in [0] * 3]
for i in range(3):
	for color in range(C):
		incom[i][color] = sum((D[x][color] for x in tri[i]))
ans = 1 << 30
for p in permutations(range(C), 3):
	t = sum((incom[x][y] for (x, y) in enumerate(p)))
	if t < ans:
		ans = t
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
c = [list(map(int, input().split())) for i in range(N)]
count = [[0] * C for i in range(3)]
for i in range(1, N + 1):
	for j in range(1, N + 1):
		count[(i + j) % 3][c[i - 1][j - 1] - 1] += 1
ans = 10 ** 10
for i in range(C):
	for j in range(C):
		if i == j:
			continue
		for k in range(C):
			if i == k or j == k:
				continue
			tmp = 0
			for x in range(C):
				tmp += D[x][i] * count[0][x] + D[x][j] * count[1][x] + D[x][k] * count[2][x]
			if ans > tmp:
				ans = tmp
print(ans)


(N, C) = map(int, input().split())
d = [list(map(int, input().split())) for i in range(C)]
c = [list(map(int, input().split())) for i in range(N)]
cnt = [[0] * C for i in range(3)]
for i in range(N):
	for j in range(N):
		cnt[(i + j + 2) % 3][c[i][j] - 1] += 1
ans = float('inf')
for c1 in range(C):
	for c2 in range(C):
		if c1 == c2:
			continue
		for c3 in range(C):
			if c1 == c3 or c2 == c3:
				continue
			tmp = 0
			for i in range(3):
				for j in range(C):
					tmp += d[j][[c1, c2, c3][i]] * cnt[i][j]
			ans = min(ans, tmp)
print(ans)


(n, m) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(m)]
c = [list(map(int, input().split())) for _ in range(n)]
ans0 = [0]
ans1 = [0]
ans2 = [0]
for k in range(1, m + 1):
	a0 = 0
	a1 = 0
	a2 = 0
	for i in range(n):
		for j in range(n):
			if (i + j + 2) % 3 == 0:
				a0 += d[c[i][j] - 1][k - 1]
			elif (i + j + 2) % 3 == 1:
				a1 += d[c[i][j] - 1][k - 1]
			else:
				a2 += d[c[i][j] - 1][k - 1]
	ans0.append(a0)
	ans1.append(a1)
	ans2.append(a2)
ans = float('inf')
import itertools
for (x, y, z) in itertools.permutations(range(1, m + 1), 3):
	ans = min(ans, ans0[x] + ans1[y] + ans2[z])
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
cst = [[0, 0, 0] for i in range(C)]
for clr in range(1, C + 1):
	for i in range(N):
		for j in range(N):
			cst[clr - 1][(i + j + 2) % 3] += D[c[i][j] - 1][clr - 1]
ans = 10 ** 10
for i in range(C):
	for j in range(C):
		for k in range(C):
			if i == j or i == k or j == k:
				continue
			ans = min(ans, cst[i][0] + cst[j][1] + cst[k][2])
print(ans)


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]
n = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		n[(i + j) % 3][c[i][j]] += 1
ans = 500 * 500 * 1000
for c0 in range(C):
	for c1 in range(C):
		if c1 == c0:
			continue
		for c2 in range(C):
			if c2 in (c0, c1):
				continue
			score = 0
			for a in range(C):
				score += n[0][a] * D[a][c0] + n[1][a] * D[a][c1] + n[2][a] * D[a][c2]
			ans = min(ans, score)
print(ans)


import itertools
(N, C) = map(int, input().split())
L = [[0 for i in range(C)] for j in range(3)]
D = []
for i in range(C):
	D.append([int(x) for x in input().split()])
for i in range(N):
	s = [int(x) - 1 for x in input().split()]
	for j in range(N):
		L[(i + j) % 3][s[j]] += 1
ans = float('inf')
for per in itertools.permutations(range(C), 3):
	kans = sum((sum((D[x][per[i]] * L[i][x] for x in range(C))) for i in range(3)))
	ans = min(ans, kans)
print(ans)


from collections import defaultdict
from itertools import permutations
(N, C) = map(int, input().split())
D = []
for _ in range(C):
	D.append(list(map(int, input().split())))
c = []
for _ in range(N):
	c.append(list(map(int, input().split())))
P = [defaultdict(int) for _ in range(3)]
for i in range(N):
	for j in range(N):
		P[(i + j) % 3][c[i][j] - 1] += 1
ans = float('inf')
for L in permutations([i for i in range(C)], 3):
	cnt = 0
	for i in range(3):
		for j in range(C):
			cnt += P[i][j] * D[j][L[i]]
	ans = min(ans, cnt)
print(ans)


from itertools import *
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in [0] * C]
tri = [[0] * C for _ in [0] * 3]
for i in range(N):
	for (j, x) in enumerate(map(int, input().split())):
		tri[(i + j) % 3][x - 1] += 1
res = 1 << 30
for p in permutations(range(C), 3):
	tt = sum((D[l][p[m]] * tri[m][l] for l in range(C) for m in range(3)))
	if tt < res:
		res = tt
print(res)


def main():
	from itertools import permutations
	(N, C) = list(map(int, input().split()))
	change_cost = [[int(x) for x in input().split()] for _ in range(C)]
	init_color = [[int(x) - 1 for x in input().split()] for _ in range(N)]
	ctr = [[0] * C for _ in range(3)]
	for r in range(N):
		for c in range(N):
			p = (r + c) % 3
			color = init_color[r][c]
			ctr[p][color] += 1
	mi = 1000 * 500 * 500 + 1
	for perm in permutations(list(range(C)), r=3):
		it = iter(perm)
		t = 0
		for p in range(3):
			color_to_be = next(it)
			for (color, count) in enumerate(ctr[p]):
				t += change_cost[color][color_to_be] * count
		mi = min(mi, t)
	print(mi)

def __starting_point():
	main()
__starting_point()


from itertools import permutations
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
t = [[0] * C for _ in range(3)]
for i in range(N):
	for j in range(N):
		t[(i + j) % 3][c[i][j] - 1] += 1
ans = 1001001001
for (i, j, k) in permutations(range(C), 3):
	tmp = 0
	for l in range(C):
		tmp += D[l][i] * t[0][l]
	for l in range(C):
		tmp += D[l][j] * t[1][l]
	for l in range(C):
		tmp += D[l][k] * t[2][l]
	ans = min(ans, tmp)
print(ans)


from collections import Counter
from itertools import permutations
import sys
input = sys.stdin.buffer.readline
(N, C) = map(int, input().split())
D = [[int(x) for x in input().split()] for _ in range(C)]
cnt = [Counter() for _ in range(3)]
for i in range(N):
	c = [int(x) - 1 for x in input().split()]
	for j in range(3):
		cnt[j].update(c[(3 - (i + 2) + j) % 3::3])
ans = 1000 * 500 * 500 + 5
for p in permutations(range(C), 3):
	s = 0
	for j in range(3):
		for (k, v) in cnt[j].items():
			s += D[k][p[j]] * v
	ans = min(ans, s)
print(ans)


(N, C) = [int(x) for x in input().split()]
D = [[int(x) for x in input().split()] for _ in range(C)]
C_grid = [[int(x) for x in input().split()] for _ in range(N)]
li = [[0] * C for _ in range(3)]
for (i, s) in enumerate(C_grid):
	for (j, c) in enumerate(s):
		li[(i + j) % 3][c - 1] += 1
ans = float('inf')
for x in range(C):
	for y in range(C):
		for z in range(C):
			diff = 0
			if x == y or y == z or x == z:
				continue
			for i in range(C):
				diff += li[0][i] * D[i][x]
				diff += li[1][i] * D[i][y]
				diff += li[2][i] * D[i][z]
			ans = min(diff, ans)
print(ans)


(N, C) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
from collections import defaultdict
cd = [defaultdict(int), defaultdict(int), defaultdict(int)]
for i in range(N):
	for j in range(N):
		k = (i + 1 + j + 1) % 3
		cd[k][c[i][j]] += 1
ans = 10 ** 10
import itertools
for p in itertools.permutations(list(range(C)), 3):
	iwa = 0
	for ci in cd[0].items():
		iwa += d[ci[0] - 1][p[0]] * ci[1]
	for ci in cd[1].items():
		iwa += d[ci[0] - 1][p[1]] * ci[1]
	for ci in cd[2].items():
		iwa += d[ci[0] - 1][p[2]] * ci[1]
	ans = min(ans, iwa)
print(ans)


from itertools import permutations
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
cnt = [[0] * C for _ in range(3)]
for h in range(N):
	for (w, c) in enumerate(map(int, input().split())):
		cnt[(h + w) % 3][c - 1] += 1
ans = 10 ** 18
for perm in permutations(range(C), r=3):
	cost = 0
	for (c, ns) in zip(perm, cnt):
		for fr in range(C):
			if fr == c:
				continue
			cost += D[fr][c] * ns[fr]
	ans = min(ans, cost)
print(ans)


def main():
	from sys import stdin

	def input():
		return stdin.readline().strip()
	(n, c) = map(int, input().split())
	d = [list(map(int, input().split())) for _ in range(c)]
	color = [list(map(int, input().split())) for _ in range(n)]
	counters = [[0] * c for _ in range(3)]
	for i in range(n):
		for j in range(n):
			counters[(i + j) % 3][color[i][j] - 1] += 1
	cost = []
	for group in counters:
		l = []
		for i in range(c):
			num = 0
			for j in range(c):
				num += d[j][i] * group[j]
			l.append((num, i))
		l.sort()
		cost.append(l[:3])
	ans = 10 ** 9
	for i in range(3):
		for j in range(3):
			for k in range(3):
				if cost[0][i][1] != cost[1][j][1] and cost[1][j][1] != cost[2][k][1] and (cost[2][k][1] != cost[0][i][1]):
					if ans > cost[0][i][0] + cost[1][j][0] + cost[2][k][0]:
						ans = cost[0][i][0] + cost[1][j][0] + cost[2][k][0]
	print(ans)
main()


(N, C) = map(int, input().split())
D = []
for i in range(C):
	t = list(map(int, input().split()))
	D.append(t)
c = []
for i in range(N):
	t = list(map(int, input().split()))
	c.append(t)
Dsum = []
for k in range(C):
	ccc = [0, 0, 0]
	for i in range(N):
		for j in range(N):
			ccc[(i + j) % 3] += D[c[i][j] - 1][k]
	Dsum.append(ccc)
ans = 9876543210
for i in range(C):
	for j in range(C):
		for k in range(C):
			if i != j and j != k and (k != i):
				ans = min(ans, Dsum[i][0] + Dsum[j][1] + Dsum[k][2])
print(ans)


(n, c) = list(map(int, input().split()))
diff = [list(map(int, input().split())) for _ in range(c)]
color = [list(map(int, input().split())) for _ in range(n)]
dic = [[0] * c for _ in range(3)]
for i in range(n):
	for j in range(n):
		dic[(i + j) % 3][color[i][j] - 1] += 1
result = 10 ** 9
for aa in range(c):
	a_cost = 0
	for j in range(c):
		a_cost += dic[0][j] * diff[j][aa]
	for bb in range(c):
		if aa != bb:
			b_cost = 0
			for j in range(c):
				b_cost += dic[1][j] * diff[j][bb]
			for cc in range(c):
				if aa != bb and bb != cc and (cc != aa):
					c_cost = 0
					for j in range(c):
						c_cost += dic[2][j] * diff[j][cc]
					result = min(result, a_cost + b_cost + c_cost)
print(result)


import itertools
(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
cost = [[0 for _ in range(C)] for _ in range(3)]
for cc in range(C):
	for i in range(N):
		for j in range(N):
			cost[(i + j) % 3][cc] += D[c[i][j] - 1][cc]
answer = []
comb = [i for i in range(C)]
for v in itertools.permutations(comb, 3):
	answer.append(sum([cost[j][v[j]] for j in range(3)]))
print(min(answer))


(N, C) = map(int, input().split())
D = [list(map(int, input().split())) for i in range(C)]
c_ = [list(map(int, input().split())) for i in range(N)]
c = [[] for i in range(3)]
for i in range(N):
	for j in range(N):
		k = (i + 1 + (j + 1)) % 3
		c[k].append(c_[i][j])
d = [[0] * C for i in range(3)]
for i in range(C):
	for j in range(3):
		for k in range(len(c[j])):
			d[j][i] += D[c[j][k] - 1][i]
ans = 10 ** 17
for i in range(C):
	for j in range(C):
		for k in range(C):
			if (i - j) * (j - k) * (k - i) == 0:
				continue
			ans = min(ans, d[0][i] + d[1][j] + d[2][k])
print(ans)