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

Solution (Python):

N, C = 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)

Solution (Python):

N, C = 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)

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

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





if __name__ == "__main__":
    main()

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

Solution (Python):
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 z.keys():
                z[now] = 1
            else:
                z[now] += 1
        if q == 1:
            if now not in o.keys():
                o[now] = 1
            else:
                o[now] += 1
        if q == 2:
            if now not in t.keys():
                t[now] = 1
            else:
                t[now] += 1

ans = inf
for i, j, l in itertools.permutations(range(C), 3):
    tmp = 0
    for k, v in z.items():
        tmp += v * D[k][i]
    for k, v in o.items():
        tmp += v * D[k][j]
    for k, v in t.items():
        tmp += v * D[k][l]
    ans = min(tmp, ans)
print(ans)

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

Solution (Python):
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 in range(n):
    for j in range(n):
        mod = (i + j) % 3
        dcnt[mod][cmat[i][j] - 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)

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

Solution (Python):
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):
    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[k][tgt] * cnt[k] for k in cnt)
    ans = min(ans, tmp)
print(ans)

Solution (Python):
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):
    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[k][tgt] * cnt[k] for k in cnt)
    ans = min(ans, tmp)
print(ans)

Solution (Python):
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 = 10 ** 9
for color in permutations(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)

Solution (Python):
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):
    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 ci, cnt in zip(color, dcnt):
        tmp += sum(d[k][ci] * cnt[k] for k in cnt)
    ans = min(ans, tmp)
print(ans)

Solution (Python):
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 = 10 ** 9
for color in permutations(range(c), 3):
    tmp = 0
    for ci, cnt in zip(color, dcnt):
        tmp += sum(d[k][ci] * cnt[k] for k in cnt)
    ans = min(ans, tmp)
print(ans)

Solution (Python):
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 = 10 ** 9
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)

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

Solution (Python):
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(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(range(C), 3):
        ans = min(a[0][i] + a[1][j] + a[2][k], ans)

    print(ans)

if __name__ == '__main__':
    resolve()

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

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

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)]
sum_val = [[0] * C for _ in range(3)]

for color in range(1, C + 1):
    for i in range(N):
        for j in range(N):
            sum_val[(i + j) % 3][color - 1] += D[c[i][j] - 1][color - 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
            ans = min(ans, sum_val[0][i] + sum_val[1][j] + sum_val[2][k])
print(ans)

Solution (Python):
from itertools import permutations

import numpy as np
from numba import njit, i8


@njit(i8[:, :](i8, i8, i8[:, :], i8[:, :]), cache=True)
def calc_cost(N, C, D, c):
    cost = np.zeros((C, 3), dtype=np.int64)
    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]
    return cost


N, C, *Dc = map(int, open(0).read().split())
D = np.array(Dc[: C * C], dtype=np.int64).reshape(C, C)
c = np.array(Dc[C * C :], dtype=np.int64).reshape(N, N)
cost = calc_cost(N, C, D, c)

ans = min(
    sum(cost[c][i] for i, c in enumerate(colors))
    for colors in permutations(range(C), 3)
)
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)]
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)

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

Solution (Python):
import sys

from collections import Counter


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


def input_int():
    return int(input())


def input_int_list():
    return [int(i) for i in input().split()]


def main():
    n, c = input_int_list()
    grid = []
    discomfort = []

    for _ in range(c):
        discomfort.append(input_int_list())

    for _ in range(n):
        grid.append(input_int_list())

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

    
    for i in range(n):
        for j in range(n):
            if (i + j + 2) % 3 == 0:
                c0.append(grid[i][j])
            elif (i + j + 2) % 3 == 1:
                c1.append(grid[i][j])
            else:
                c2.append(grid[i][j])

    
    c0 = Counter(c0)
    c1 = Counter(c1)
    c2 = Counter(c2)

    ans = float("inf")

    
    for x in range(1, c + 1):
        for y in range(1, c + 1):
            for z in range(1, c + 1):
                if x == y or y == z or z == x:
                    continue
                tmp = 0
                for k, v in c0.items():
                    if k == x:
                        continue
                    else:
                        tmp += discomfort[k - 1][x - 1] * v

                for k, v in c1.items():
                    if k == y:
                        continue
                    else:
                        tmp += discomfort[k - 1][y - 1] * v

                for k, v in c2.items():
                    if k == z:
                        continue
                    else:
                        tmp += discomfort[k - 1][z - 1] * v

                ans = min(ans, tmp)

    print(ans)

    return


if __name__ == "__main__":
    main()

Solution (Python):
from itertools import permutations
N,Col = map(int,input().split())
D = [[0 for _ in range(Col+1)]]
for _ in range(Col):
    d = list(map(int,input().split()))
    d.insert(0,0)
    D.append(d)
A = [list(map(int,input().split())) for _ in range(N)]
C = {0:{},1:{},2:{}}
for i in range(N):
    for j in range(N):
        c = (i+j)%3
        a = A[i][j]
        if a not in C[c]:
            C[c][a] = 0
        C[c][a] += 1
dmin = 10**10
for x in permutations(range(1,Col+1),3):
    cnt0 = 0
    for c in C[0]:
        cnt0 += C[0][c]*D[c][x[0]]
    cnt1 = 0
    for c in C[1]:
        cnt1 += C[1][c]*D[c][x[1]]
    cnt2 = 0
    for c in C[2]:
        cnt2 += C[2][c]*D[c][x[2]]
    dmin = min(dmin,cnt0+cnt1+cnt2)
print(dmin)

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)]
for i, l in enumerate(C):
    l = [x-1 for x in l]
    C[i] = l

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

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

    '''
    
    
    for k in range(c):
        for i in range(c):
            for j in range(c):
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]
    '''

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

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

    '''
    
    
    for k in range(c):
        for i in range(c):
            for j in range(c):
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]
    '''

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

Solution (Python):


import sys 
from itertools import permutations
from collections import defaultdict
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N,C = map(int,readline().split())
D = []
for _ in range(C):
    row = list(map(int,readline().split()))
    D.append(row)
data = []
for _ in range(N):
    row = list(map(int,readline().split()))
    data.append(row)

INF = 10**31
ans = INF
X = defaultdict(int)
Y = defaultdict(int)
Z = defaultdict(int)

for i in range(N):
    for j in range(N):
        pre_c = data[i][j]-1
        if (i+j) % 3 == 0:
            X[pre_c] += 1   
        elif (i+j) % 3 == 1:
            Y[pre_c] += 1
        else:
            Z[pre_c] += 1

M = [i for i in range(C)]
for a,b,c in permutations(M,3):
    total = 0
    for k,v in X.items():
        total += D[k][a]*v
    for k,v in Y.items():
        total += D[k][b]*v
    for k,v in Z.items():
        total += D[k][c]*v
    
    ans = min(ans,total)
print(ans)

Solution (Python):
from collections import defaultdict
N, C = map(int, input().split())
D = []
for i in range(C):
    K = list(map(int, input().split()))
    D.append(K)
Before = []
for i in range(N):
    K = list(map(int, input().split()))
    Before.append(K)
Num = [[0]*N for _ in range(N)]
for i in range(N):
    for j in range(N):
        Num[i][j] = (i + j + 2) % 3
Zero = defaultdict(int)
One = defaultdict(int)
Two = defaultdict(int)

for i in range(N):
    for j in range(N):
        if Num[i][j] == 0:
            Zero[Before[i][j] - 1] += 1
        elif Num[i][j] == 1:
            One[Before[i][j] - 1] += 1
        else:
            Two[Before[i][j] - 1] += 1
Cost = [[0]*C for _ in range(3)]
for i in range(C):
    for k, v in Zero.items():
        Cost[0][i] += v * D[k][i]
    for k, v in One.items():
        Cost[1][i] += v * D[k][i]
    for k, v in Two.items():
        Cost[2][i] += v * D[k][i]
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):
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)]
lis = [[] for _ in range(3)]

for i in range(N):
    for j in range(N):
        lis[(i+j+2) % 3].append(c[i][j])

val = [[] for _ in range(3)]
for i in range(3):
    for j in range(C):
        cnt = 0
        for k in lis[i]:
            
            cnt += D[k-1][j]
        val[i].append(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,val[0][i]+val[1][j]+val[2][k])
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())))
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))

Solution (Python):





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)

Solution (Python):
from itertools import permutations, product
INF = float("inf")
N,C=map(int, input().split())
D=[[INF]*(C+1) for _ in range(C+1)]
c = [[-1]*(N+1) for _ in range(N+1)]
for i in range(1, C+1):
    tmp=list(map(int, input().split()))
    for j in range(1, C+1):
        D[i][j] = tmp[j-1]
for i in range(1, N+1):
    tmp=list(map(int, input().split()))
    for j in range(1, N+1):
        c[i][j] = tmp[j-1]
res0 = []
res1 = []
res2 = []
for i in range(1, N+1):
    for j in range(1, N+1):
        if (i+j)%3==0:
            res0.append((i,j))
        elif (i+j)%3==1:
            res1.append((i,j))
        else:
            res2.append((i,j))
ans = INF
dc0 = []
dc1 = []
dc2 = []
for nx in range(1,C+1):
    d0 = 0
    d1 = 0
    d2 = 0
    for i,j in res0:
        d0 += D[c[i][j]][nx]
    for i,j in res1:
        d1 += D[c[i][j]][nx]
    for i,j in res2:
        d2 += D[c[i][j]][nx]
    dc0.append((d0, nx))
    dc1.append((d1, nx))
    dc2.append((d2, nx))
dc0.sort()
dc1.sort()
dc2.sort()

for i, j, k in product(range(0, 3), repeat=3):
    c0 = dc0[i][1]
    c1 = dc1[j][1]
    c2 = dc2[k][1]
    if c0 == c1 or c1 == c2 or c2 == c0:
        continue
    disgust = 0
    for i, j in res0:
        disgust += D[c[i][j]][c0]
    for i, j in res1:
        disgust += D[c[i][j]][c1]
    for i, j in res2:
        disgust += D[c[i][j]][c2]
    ans = min(ans, disgust)
print(ans)

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

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


cnt = [[0 for _ in range(C)]for _ in range(3)]

for i in range(1, N + 1):
    for j in range(1, N + 1):
        cnt[(i + j) % 3][c[i - 1][j - 1] - 1] += 1


ans = 10**18


for c0 in range(C):
    for c1 in range(C):
        for c2 in range(C):
            
            if c0 == c1 or c1 == c2 or c2 == c0:
                continue

            cost = 0
            
            for i, n in enumerate(cnt[0]):
                cost += n * D[i][c0]
            
            for i, n in enumerate(cnt[1]):
                cost += n * D[i][c1]
            
            for i, n in enumerate(cnt[2]):
                cost += n * D[i][c2]

            ans = min(ans, cost)

print(ans)