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

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

if __name__ == "__main__":
  main()

Solution (Python):
import sys
input = sys.stdin.buffer.readline
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)

Solution (Python):
import sys
from itertools import permutations

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


def main():
    N, C = map(int, input().split())
    D = [[0] * (C + 1)]
    for _ in range(C):
        d = [0] + list(map(int, input().split()))
        D.append(d)

    grid = [[0] * (N + 1)]
    for _ in range(N):
        g = [0] + list(map(int, input().split()))
        grid.append(g)

    cost = {0: [], 1: [], 2: []}
    ans = INF
    for c in range(1, C + 1):
        cost0 = 0
        cost1 = 0
        cost2 = 0
        for i in range(1, N + 1):
            for j in range(1, N + 1):
                if (i + j) % 3 == 0:
                    cost0 += D[grid[i][j]][c]
                elif (i + j) % 3 == 1:
                    cost1 += D[grid[i][j]][c]
                elif (i + j) % 3 == 2:
                    cost2 += D[grid[i][j]][c]

        cost[0].append((c, cost0))
        cost[1].append((c, cost1))
        cost[2].append((c, cost2))

    cost[0].sort(key=lambda x: x[1])
    cost[1].sort(key=lambda x: x[1])
    cost[2].sort(key=lambda x: x[1])

    ans = INF
    for c0, cost0 in cost[0][:3]:
        for c1, cost1 in cost[1][:3]:
            for c2, cost2 in cost[2][:3]:
                if c0 == c1 or c1 == c2 or c2 == c0:
                    continue

                tmp = cost0 + cost1 + cost2
                if tmp < ans:
                    ans = tmp

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import sys


def input():
    return sys.stdin.readline().strip()


sys.setrecursionlimit(20000000)

MOD = 10 ** 9 + 7
INF = float("inf")


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


if __name__ == "__main__":
    main()

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

Solution (Python):
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 = float('inf')

for c1, c2, c3 in itertools.permutations(range(C), 3):
    ans = min(ans, memo[0][c1] + memo[1][c2] + memo[2][c3])

print(ans)

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

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

Solution (Python):

import sys
from itertools import permutations
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,C=map(int,input().split())
    D=[tuple(map(int,input().split())) for _ in range(C)]
    c=[tuple(map(int1,input().split())) for _ in range(N)]
    l=[[0]*C for _ in range(3)]
    for i in range(N):
        for j in range(N):
            l[(i+j)%3][c[i][j]]+=1
    ans=INF
    for t in permutations(range(C),3):
        tmp=0
        for i in range(3):
            for j in range(C):
                tmp+=l[i][j]*D[j][t[i]]
        ans=min(ans,tmp)
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
from collections import defaultdict

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

mod_0=defaultdict(int)
mod_1=defaultdict(int)
mod_2=defaultdict(int)

for i in range(N):
    for j in range(N):
        n=(i+j+2)%3
        if n==0:
            mod_0[grid[i][j]]+=1
        elif n==1:
            mod_1[grid[i][j]]+=1
        else:
            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 mod_0.items():
                total+=D[prev-1][i]*cnt
            for prev,cnt in mod_1.items():
                total+=D[prev-1][j]*cnt
            for prev,cnt in mod_2.items():
                total+=D[prev-1][k]*cnt
            
            ans=min(ans,total)
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 _ 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)

Solution (Python):

from collections import defaultdict

N,C = 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 mod_0.items():
                total += D[prev-1][i] * cnt
            for prev,cnt in mod_1.items():
                total += D[prev-1][j] * cnt
            for prev,cnt in mod_2.items():
                total += D[prev-1][k] * cnt

            ans = min(ans, total)

print(ans)

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

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

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

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

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)

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

res=[[] for i in range(3)]
for mod in range(3):
    for color in range(C):
        dif=0
        for i in range(N):
            for j in range(N):
                if (i+j+2)%3==mod:
                    dif+=D[c[i][j]-1][color]
        res[mod].append([dif,color])
for i in range(3):
    res[i].sort()
ans=10**10
for i in range(3):
    for j in range(3):
        for k in range(3):
            if((res[0][i][1]!=res[1][j][1])and(res[1][j][1]!=res[2][k][1])and(res[2][k][1]!=res[0][i][1])):
                ans=min(ans,res[0][i][0]+res[1][j][0]+res[2][k][0])
print(ans)

Solution (Python):
INF = float('inf')
N, C = map(int, input().split())
D = list() 
graph = list()
for i in range(C):
  D.append(list(map(int, input().split())))
for i in range(N):
  graph.append(list(map(int, input().split())))
E = [[0] * C for _ in range(3)] 
for c in range(C):
  for x in range(N):
    for y in range(N):
      p = (x+y+2)%3
      cxy = graph[x][y]-1
      E[p][c] += D[cxy][c]
F = [[[INF]*2 for _ in range(3)] for _ in range(3)] 

for i in range(3):
  for j in range(C):
    if(E[i][j] < F[i][0][1]):
      F[i][2] = F[i][1]
      F[i][1] = F[i][0]
      F[i][0] = [j, E[i][j]]
    elif(E[i][j] < F[i][1][1]):
      F[i][2] = F[i][1]
      F[i][1] = [j, E[i][j]]
    elif(E[i][j] < F[i][2][1]):
      F[i][2] = [j, E[i][j]]
      
ans = INF
for i in range(3):
  for j in range(3):
    for k in range(3):
      c0 = F[0][i][0]
      c1 = F[1][j][0]
      c2 = F[2][k][0]
      if(c0 != c1 and c1 != c2 and c2 != c0):
        ans = min(ans, F[0][i][1]+F[1][j][1]+F[2][k][1])
print(ans)

Solution (Python):






def main():
    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()))
        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())

Solution (Python):
import itertools
n,c = map(int,input().split())
dij = [[int(i) for i in input().split()] for j in range(c)]
cij = [[int(i) for i in input().split()] for j in range(n)]

c0 = []
c1 = []
c2 = []


for i in range(1,c+1):
    c0_tmp = 0
    c1_tmp = 0
    c2_tmp = 0
    for j in range(n*n):
        c_num = cij[j//n][j%n]
        cnt = j//n + j % n + 2
        if cnt % 3 == 0:
            if c_num != i:
                
                c0_tmp += dij[c_num-1][i-1]
        elif cnt % 3 == 1:
            if c_num != i:
                c1_tmp += dij[c_num-1][i-1]
            
        else:
            if c_num != i:
                c2_tmp += dij[c_num-1][i-1]
            
    c0.append(c0_tmp)
    c1.append(c1_tmp)
    c2.append(c2_tmp)
        
li = list(itertools.permutations(range(1, c+1),3))

ans = 10**18

for i in range(len(li)):
    tmp = 0
    
    tmp += c0[li[i][0]-1]
    tmp += c1[li[i][1]-1]
    tmp += c2[li[i][2]-1]
    
    
    ans = min(ans,tmp)

print(ans)

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

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

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

Solution (Python):
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)
  
if __name__ == "__main__":
  main()

Solution (Python):
import collections
N,C=map(int,input().split())
cost=[list(map(int,input().split())) for _ in range(C)]
table=[list(map(int,input().split())) for _ in range(N)]
l=[[] for _ in range(3)]
costs=[[] for _ in range(3)]

for i in range(N):
    for j in range(N):
        l[(i+j)%3].append(table[i][j])

c1=collections.Counter(l[0])
c2=collections.Counter(l[1])
c3=collections.Counter(l[2])
costs=[[] for _ in range(3)]
for i in range(C):
    for j in range(3):
        buf=0
        for k in l[j]:
            buf=buf+cost[k-1][i]
        costs[j].append(buf)

mi=float("inf")
for i in range(C):
    for j in range(C):
        for k in range(C):
            if (i!=j)and(j!=k)and(i!=k):
                mi=min(mi,costs[0][i]+costs[1][j]+costs[2][k])
print(mi)

Solution (Python):
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 = 1e100
for x,y,z in itertools.permutations(range(C),3):
    ans = min(ans, delta[0][x] + delta[1][y] + delta[2][z])
print(ans)

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

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

Solution (Python):



from itertools import combinations, permutations

def main():
  n, nc = map(int, input().split())
  md = [list(map(int, input().split())) for _ in range(nc)]
  mc = [list(map(lambda c: int(c)-1, 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(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)
    
      
  

if __name__=='__main__':
  main()

Solution (Python):
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)]
grid1 = []
grid2 = []
grid3 = []
ans = float('inf')
for i in range(N):
    for k in range(N):
        tmp = grid[i][k]
        tmp2 = i + k
        if tmp2 % 3 == 1:
            grid1.append(tmp)
        elif tmp2 % 3 == 2:
            grid2.append(tmp)
        else:
            grid3.append(tmp)
sum1 = sum(grid1)
sum2 = sum(grid2)
sum3 = sum(grid3)
tmp1 = [sum1]*C
tmp2 = [sum2]*C
tmp3 = [sum3]*C
for i in range(C):
    for k in grid1:
        tmp1[i] = tmp1[i] - k + D[k-1][i]
for i in range(C):
    for k in grid2:
        tmp2[i] = tmp2[i] - k + D[k-1][i]
for i in range(C):
    for k in grid3:
        tmp3[i] = tmp3[i] - k + D[k-1][i]
for i in range(C):
    for k in range(C):
        if i == k:
            continue
        for l in range(C):
            if i == l or k == l:
                continue
            ans = min(ans,tmp1[i]+tmp2[k]+tmp3[l])
print(ans)

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

Solution (Python):
import sys
input = sys.stdin.buffer.readline
from itertools import permutations

def main():
    N,C = map(int,input().split())
    D = [list(map(int,input().split())) for _ in range(C)]
    col = [list(map(int,input().split())) for _ in range(N)]
    
    mod_color = [[0]*C,[0]*C,[0]*C]
    for i in range(N):
        for j in range(N):
            mod_color[(i+j)%3][col[i][j]-1] += 1

    ans = 10**10
    for x,y,z in permutations(range(C),3):
        ret = 0
        ret += sum(mod_color[0][i]*D[i][x] for i in range(C))
        ret += sum(mod_color[1][i]*D[i][y] for i in range(C))
        ret += sum(mod_color[2][i]*D[i][z] for i in range(C))
        ans = min(ans,ret)
        
    print(ans)
    
if __name__ == "__main__":
    main()

Solution (Python):















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



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)

Solution (Python):















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



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)

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