Problem:
 Score : 400 points    Problem Statement There is a grid with N rows and N columns of squares. Let (i,j) be the square at the i -th row from the top and the j -th column from the left.  These squares have to be painted in one of the C colors from Color 1 to Color C . Initially, (i,j) is painted in Color c_{i,j} .  We say the grid is a good grid when the following condition is met for all i,j,x,y satisfying 1 \leq i,j,x,y \leq N :   If (i+j) \% 3=(x+y) \% 3 , the color of (i,j) and the color of (x,y) are the same.  If (i+j) \%  3 \neq (x+y) \% 3 , the color of (i,j) and the color of (x,y) are different.   Here, X \% Y represents X modulo Y .  We will repaint zero or more squares so that the grid will be a good grid.  For a square, the wrongness when the color of the square is X before repainting and Y after repainting, is D_{X,Y} .  Find the minimum possible sum of the wrongness of all the squares.      Constraints  1 \leq N \leq 500  3 \leq C \leq 30  1 \leq D_{i,j} \leq 1000 (i \neq j),D_{i,j}=0 (i=j)  1 \leq c_{i,j} \leq C  All values in input are integers.         Input Input is given from Standard Input in the following format:  N  C  D_{1,1}  ...  D_{1,C}  :  D_{C,1}  ...  D_{C,C}  c_{1,1}  ...  c_{1,N}  :  c_{N,1}  ...  c_{N,N}       Output If the minimum possible sum of the wrongness of all the squares is x , print x .        Sample Input 1 2 3
0 1 1
1 0 1
1 4 0
1 2
3 3      Sample Output 1 3   Repaint (1,1) to Color 2 . The wrongness of (1,1) becomes D_{1,2}=1 .  Repaint (1,2) to Color 3 . The wrongness of (1,2) becomes D_{2,3}=1 .  Repaint (2,2) to Color 1 . The wrongness of (2,2) becomes D_{3,1}=1 .   In this case, the sum of the wrongness of all the squares is 3 .  Note that D_{i,j} \neq D_{j,i} is possible.       Sample Input 2 4 3
0 12 71
81 0 53
14 92 0
1 1 2 1
2 1 1 2
2 2 1 3
1 1 2 2      Sample Output 2 428

Solution (Python):
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)

Solution (Python):
from collections import defaultdict
import itertools
n, c = 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 diago0.items():
        cost0[i] += D[k][i]*v
for i in range(c):
    for k, v in diago1.items():
        cost1[i] += D[k][i]*v
for i in range(c):
    for k, v in diago2.items():
        cost2[i] += D[k][i]*v

INF = 10**18
ans = INF
for trio in itertools.combinations(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)

Solution (Python):
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)

Solution (Python):
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
input = sys.stdin.buffer.readline





def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))


from itertools import permutations



def main():
	n,c=MI()
	D=[[0]*(c+1)]
	for _ in range(c):
		D.append([0]+LI())
	
	
	C=[[0]*(n+1)]
	for _ in range(n):
		C.append([0]+LI())
	
	
	li=[[0]*(c+1) for _ in range(3)]
	for i in range(1,n+1):
		for j in range(1,n+1):
			li[(i+j)%3][C[i][j]]+=1
	
	
	ans=10**10
	
	for ii in permutations(range(1,c+1),3):
		ret=0
		
		for a in range(3):
			for b in range(1,c+1):
				
				ret+=li[a][b]*D[b][ii[a]]
		
		ans=min(ans,ret)
	print(ans)
	
	
	
	
	
	
	

if __name__ == "__main__":
	main()

Solution (Python):
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)

if __name__=="__main__":
    main()

Solution (Python):
from sys import stdin
def main():
    
    readline=stdin.readline
    n,max_c=map(int,readline().split())
    d=[list(map(int,readline().split())) for _ in range(max_c)]
    c=[list(map(lambda x:int(x)-1,readline().split())) for _ in range(n)]

    
    color_table=[[0]*max_c for _ in range(3)]
    for color in range(max_c):
        for i in range(n):
            for j in range(n):
                color_table[(i+j+2)%3][color]+=d[c[i][j]][color]

    
    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)

if __name__=="__main__":
    main()

Solution (Python):
from collections import Counter
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)]


m0 = Counter()
c0 = 0
m1 = Counter()
c1 = 0
m2 = Counter()
c2 = 0
for i in range(N):
    for j in range(N):
        if ((i+1)+(j+1)) % 3 == 0:
            m0[c[i][j]] += 1
            c0 += 1
        elif ((i+1)+(j+1)) % 3 == 1:
            m1[c[i][j]] += 1
            c1 += 1
        else:
            m2[c[i][j]] += 1
            c2 += 1

m = [m0, m1, m2]
cnt = [c0, c1, c2]

ans = float('inf')
for perm in itertools.permutations([i for i in range(1, C+1)], 3):
    tmp = 0
    for i in range(3):
        for k, v in m[i].items():
            if k != perm[i]:
                tmp += D[k-1][perm[i]-1] * v
    ans = min(ans, tmp)
print(ans)

Solution (Python):
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 = 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(range(c), 3):
    tmp = 0
    for i in range(3):
        tmp += calc(color[i], item[i], d_mtx)
    ret = min(ret, tmp)

print(ret)

Solution (Python):

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)

Solution (Python):

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(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)

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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):
            for r in range(3):
                if (i+j)%3 == r: cnt[r][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)

Solution (Python):
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)]

cols = [[0] * c for _ in range(3)]
for i in range(n):
    for j in range(n):
        c_from = C[i][j]
        cols[(i+j)%3][c_from] += 1

from itertools import permutations
d = 1000*500*500
for p0, p1, p2 in permutations(list(range(c)), 3):
    d_ = 0
    for c_from in range(c):
        d_ += cols[0][c_from]*D[c_from][p0]
        d_ += cols[1][c_from]*D[c_from][p1]
        d_ += cols[2][c_from]*D[c_from][p2]
    d = min(d, d_)
print(d)

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
import bisect
import collections
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7

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())))

r0 = []
r1 = []
r2 = []
for i in range(N):
    for j in range(N):
        if (i+j)%3 == 0:
            r0.append(c[i][j])
        elif (i+j)%3 == 1:
            r1.append(c[i][j])
        else:
            r2.append(c[i][j])

d0 = [[]]*C
d1 = [[]]*C
d2 = [[]]*C
for color in range(C):
    s = 0
    for i in range(len(r0)):
        s += D[r0[i]-1][color]
    d0[color] = (s,color)
for color in range(C):
    s = 0
    for i in range(len(r1)):
        s += D[r1[i]-1][color]
    d1[color] = (s,color)
for color in range(C):
    s = 0
    for i in range(len(r2)):
        s += D[r2[i]-1][color]
    d2[color] = (s,color)

d0.sort()
d1.sort()
d2.sort()

ans = float("inf")
for i in range(3):
    for j in range(3):
        for k in range(3):
            if d0[i][1] != d1[j][1] and d0[i][1] != d2[k][1] and d1[j][1] != d2[k][1]:
                ans = min(ans,d0[i][0]+d1[j][0]+d2[k][0])
print(ans)

Solution (Python):
import sys
from itertools import permutations
N, C = map(int, sys.stdin.readline().rstrip().split())

d = []
for _ in range(C):
    d.append(tuple(map(int, sys.stdin.readline().rstrip().split())))

r_0 = []
r_1 = []
r_2 = []
for i in range(N):
    g = list(map(int, sys.stdin.readline().rstrip().split()))
    for j in range(N):
        if (i + j) % 3 == 0:
            r_0.append(g[j])
        elif (i + j) % 3 == 1:
            r_1.append(g[j])
        else:
            r_2.append(g[j])

def get_cost(r):
    cost = [0] * (C + 1)
    for c in range(1, C + 1):
        for i in r:
            cost[c] += d[i - 1][c - 1]

    return cost

cost_0 = get_cost(r_0)
cost_1 = get_cost(r_1)
cost_2 = get_cost(r_2)

ans = 10**18
for c_0, c_1, c_2 in permutations(range(1, C + 1), 3):
    total = cost_0[c_0] + cost_1[c_1] + cost_2[c_2]
    ans = min(ans, total)
print(ans)

Solution (Python):
from collections import defaultdict

N, C = map(int, input().split())

Disguise = [list(map(int, input().split())) for _ in range(C)]
Color = [list(map(int, input().split())) for _ in range(N)]

C0 = defaultdict(int)
C1 = defaultdict(int)
C2 = defaultdict(int)

for i in range(N):
    for j in range(N):
        if (i + j + 2) % 3 == 0:
            C0[Color[i][j]] += 1
        elif (i + j + 2) % 3 == 1:
            C1[Color[i][j]] += 1
        else:
            C2[Color[i][j]] += 1

ans = float('inf')
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
            ansi = 0
            for key, value in C0.items():
                ansi += Disguise[key - 1][x] * value
            for key, value in C1.items():
                ansi += Disguise[key - 1][y] * value
            for key, value in C2.items():
                ansi += Disguise[key - 1][z] * value
            ans = min(ansi, ans)
print(ans)

Solution (Python):
import heapq

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)]

MAXN = 500
MAXC = 30

s = [[0 for _ in range(MAXC)] for _ in range(3)]
for i in range(3):
    for co in range(c):
        for x in range(n):
            for y in range(n):
                if (x+y)%3 == i:
                    s[i][co] += d[grid[x][y]-1][co]

ans = 10**10
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, s[0][c0]+s[1][c1]+s[2][c2])
print(ans)

Solution (Python):
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)

Solution (Python):
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):
        ai = a[i]
        bi = b[i]
        for j in range(C):
            t += ai[j] * D[j][bi]
    result = min(result, t)
print(result)

Solution (Python):
n,c=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)

Solution (Python):
from sys import stdin
input = stdin.readline
import copy as cp

def VI(N, init=0):
  return [init for _ in range(N)]
def VVI(N, M, init=0):
  return [[init for _ in range(M)] for _ in range(N)]

def VD(N, init=0.0):
  return [init for _ in range(N)]
def VVD(N, M, init=0.0):
  return [[init for _ in range(M)] for _ in range(N)]

def Decimal(x):
  print("{0:.10f}".format(x))

class Pair:
  def __init__(self, x=0, y=0):
    self.first = x
    self.second = y

  def __repr__(self):
    return '{0} {1}'.format(self.first, self.second)

  def __lt__(self, pi):
    return self.first < pi.second

def POW(x, n):
  ret = 1
  while n:
    if n&1:
      ret *= x
    x *= x
    n >>= 1
  return ret

MAX_N = 505
MAX_C = 35
D = VVI(MAX_C, MAX_C)
color = VVI(MAX_N, MAX_N)

N, C = map(int, input().rstrip().split())
for i in range(C):
  tmp_list = list(map(int, input().rstrip().split()))
  for j in range(C):
    D[i][j] = tmp_list[j]

for i in range(N):
  tmp_list = list(map(int, input().rstrip().split()))
  for j in range(N):
    color[i][j] = tmp_list[j]
    color[i][j] -= 1

table = VVI(3, MAX_C)

for i in range(N*N):
  x = i % N
  y = i // N
  c = color[y][x]
  for j in range(3):
    if (x+y+2)%3 == j:
      table[j][c] += 1

ans = int(1e9+7)

def dfs(s, diff):
  global ans
  if len(s) >= 3:
    ans = min(ans, diff)
    return

  for c in range(C):
    ddiff = diff
    ss = cp.deepcopy(s)
    if c in s:
      continue

    for i in range(C):
      ddiff += table[len(s)][i] * D[i][c]
    ss.add(c)
    dfs(ss , ddiff)

s = set([])

dfs(s, 0)

print(ans)

Solution (Python):
n, c = map(int, input().split())
dl = []
for i in range(c):
    dl.append(list(map(int, input().split())))
cl = []
for i in range(n):
    cl.append(list(map(int, input().split())))

d = {i: [0]*c for i in range(3)}

for i in range(n):
    for j in range(n):
        d[(i+j)%3][int(cl[i][j])-1] += 1
cost = {i: [0]*c for i in range(3)}
for i in range(3):
    for j in range(c):
        for k in range(c):
            cost[i][j] += int(dl[k][j]) * d[i][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)

Solution (Python):


import sys










from collections import Counter              











from itertools import product, permutations  







def main():
    mod = 1000000007                
    inf = float('inf')              
    
    sys.setrecursionlimit(10**6)    
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())

    
    n, c = mi()
    color_cost = [lmi() for _ in range(c)]    

    
    
    
    
    


    group = [[] for _ in range(3)]    
    for i in range(n):
        tmp = lmi_0()    
        
        for j in range(n):
            group[(i+j)%3].append(tmp[j])
    
    zero, one, two = group
    
    zero_cnt, one_cnt, two_cnt = map(lambda x: Counter(x), group)

    ans = 10**15
    
    for color_zero, color_one, color_two in permutations(range(c), r=3):
        cost = 0
        for col, v in zero_cnt.items():
            cost += v * color_cost[col][color_zero]
        for col, v in one_cnt.items():
            cost += v * color_cost[col][color_one]
        for col, v in two_cnt.items():
            cost += v * color_cost[col][color_two]
        ans = min(ans, cost)
    print(ans)



if __name__ == "__main__":
    main()

"""
O(10^7) だけど通らないっぽい <- 勘違い O(30*29*28* n) ではなく O(30*29*28* n * n) なので O(6*10^9)
辞書化の前処理で O(30*29*28 * c) = O(10**5) に
"""

Solution (Python):
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)]
    C = [0]*n
    for i, c_ in enumerate(C_):
        c_ = [x-1 for x in c_]
        C[i] = c_

    X = [[0]*c for _ in range(3)]
    for i in range(n):
        for j in range(n):
            m = (i+j)%3
            X[m][C[i][j]] += 1

    
    import itertools
    ans = 10**18
    for p in itertools.permutations(range(c), 3):
        temp = 0
        for i in range(3):
            for j in range(c):
                temp += D[j][p[i]]*X[i][j]
        ans = min(ans, temp)
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
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)]
    C = [0]*n
    for i, c_ in enumerate(C_):
        c_ = [x-1 for x in c_]
        C[i] = c_

    X = [[0]*c for _ in range(3)]
    for i in range(n):
        for j in range(n):
            m = (i+j)%3
            X[m][C[i][j]] += 1

    
    import itertools
    ans = 10**18
    for p in itertools.permutations(range(c), 3):
        temp = 0
        for i in range(3):
            for j in range(c):
                temp += D[j][p[i]]*X[i][j]
        ans = min(ans, temp)
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
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)]
    C = [0]*n
    for i, c_ in enumerate(C_):
        c_ = [x-1 for x in c_]
        C[i] = c_

    
    L = [[0]*c for _ in range(3)]
    for k in range(c):
        for i in range(n):
            for j in range(n):
                m = (i+j)%3
                x = C[i][j]
                L[m][k] += D[x][k]
                
    X = [[] for _ in range(3)]
    for j in range(3):
        for i, x in enumerate(L[j]):
            X[j].append((x, i))
    for i, x in enumerate(X):
        x.sort()
        x = x[0:3]
        X[i] = x

    
    import itertools
    ans = 10**18
    for p in itertools.product(range(3), repeat=3):
        used_col = set()
        temp = 0
        for j in range(3):
            x, i =X[j][p[j]]
            if i in used_col:
                break
            else:
                temp += x
                used_col.add(i)
        else:
            ans = min(temp, ans)
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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)]

mod0 = []
mod1 = []
mod2 = []

for i in range(N):
    for j in range(N):
        if (i+j+2) % 3 == 0:
            mod0.append(c_field[i][j])
        elif (i+j+1) % 3 == 1:
            mod1.append(c_field[i][j])
        else:
            mod2.append(c_field[i][j])

mod0 = Counter(mod0)
mod1 = Counter(mod1)
mod2 = Counter(mod2)

def calc(p):
    ret = 0
    for i, v in mod0.items():
        if i == p[0]: continue
        ret += D[i-1][p[0]-1] * v
    for i, v in mod1.items():
        if i == p[1]: continue
        ret += D[i-1][p[1]-1] * v
    for i, v in mod2.items():
        if i == p[2]: continue
        ret += D[i-1][p[2]-1] * v
    return ret
    

ans = 10 ** 30
for p in permutations(range(1,C+1), 3):
    ans = min(ans, calc(p))

print(ans)

Solution (Python):
import itertools


def main():
    N, C = list(map(int, input().split(' ')))
    D = [list(map(int, input().split(' '))) for _ in range(C)]
    grids = [list(map(lambda c: int(c) - 1, 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(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)


if __name__ == '__main__':
    main()

Solution (Python):
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)