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

cost0 = []
cost1 = []
cost2 = []
indices = [2, 0, 1]
for color in range(C):
  cost = [0, 0, 0]
  for i in range(N):
    idx = indices[i%3]
    for j in range(N):
      cost[idx] += D[c[i][j]-1][color]
      idx = (idx + 1) % 3
  cost0.append([cost[0], color])
  cost1.append([cost[1], color])
  cost2.append([cost[2], color])

cost0.sort()
cost1.sort()
cost2.sort()
ans = float('inf')
for i in range(3):
  for j in range(3):
    for k in range(3):
      if len(set([cost0[i][1], cost1[j][1], cost2[k][1]])) == 3:
        ans = min(ans, cost0[i][0]+cost1[j][0]+cost2[k][0])

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)]
x=[[0]*(C+1) for _ in range(3)]
for i in range(N):
    for j in range(N):
        x[(i+j+2)%3][c[i][j]]+=1

from itertools import permutations
ans=1<<32
for ch in permutations(range(1,C+1),3):
    ans1=0
    for i in range(3):
        for j in range(1,C+1):
            ans1+=x[i][j]*d[j-1][ch[i]-1]
    ans=min(ans,ans1)
print(ans)

Solution (Python):
N,C = map(int, input().split())

D = [[int(i) for i in input().split()] for _ in range(C)]

cnt = [[0] * C for _ in range(3)]
for i in range(1, N + 1):
    line = [int(i) for i in input().split()]
    for j, c in enumerate(line, start=1):
        cnt[(i + j) % 3][c - 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
            cost = 0
            for x in range(C):
                cost += D[x][i] * cnt[0][x]
                cost += D[x][j] * cnt[1][x]
                cost += D[x][k] * cnt[2][x]
            
            ans = min(ans, cost)

print(ans)

Solution (Python):
import sys
def main():
    input = sys.stdin.readline
    N,C=map(int, input().split())
    D=[tuple(map(int, input().split())) for _ in range(C)]
    c=[tuple(map(int, input().split())) for _ in range(N)]

    c0=[c[i][j]-1 for i in range(N) for j in range(N) if (i+j)%3==0]
    c1=[c[i][j]-1 for i in range(N) for j in range(N) if (i+j)%3==1]
    c2=[c[i][j]-1 for i in range(N) for j in range(N) if (i+j)%3==2]

    from collections import Counter
    cc=[Counter(c0), Counter(c1), Counter(c2)]

    ans = 10**10
    from itertools import permutations
    for colors in permutations(range(C), 3):
        tmp = 0
        for i,cci in enumerate(cc):
            for k,v in cci.items():
                tmp += D[k][colors[i]] * v
        ans = min(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
N,C = map(int,input().split())
D = [list(map(int,input().split())) for i in range(C)]
CS = [list(map(int,input().split())) for i in range(N)]

from collections import Counter
cs = [Counter() for _ in range(3)]
for i,row in enumerate(CS):
    for j,c in enumerate(row):
        cs[(i+j)%3][c-1] += 1

ans = float('inf')
for i in range(C):
    d1 = 0
    for c,v in cs[0].items():
        d1 += D[c][i]*v
    for j in range(C):
        if i==j: continue
        d2 = 0
        for c,v in cs[1].items():
            d2 += D[c][j]*v
        for k in range(C):
            if k==i or k==j: continue
            d3 = 0
            for c,v in cs[2].items():
                d3 += D[c][k]*v
            ans = min(ans, d1+d2+d3)
print(ans)

Solution (Python):

from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n,C = LI()
    d = LIR(C)
    c = LIR(n)
    ans = 0
    s = [[0]*C for i in range(3)]
    for i in range(n):
        for j in range(n):
            s[(i+j)%3][c[i][j]-1] += 1
    ans = float("inf")
    for x in range(C):
        bx = 1<<x
        for y in range(C):
            if x == y:
                continue
            by = 1<<y
            for z in range(C):
                if z == x or z == y:
                    continue
                cost = 0
                for j in range(C):
                    cost += s[0][j]*d[j][x]
                    cost += s[1][j]*d[j][y]
                    cost += s[2][j]*d[j][z]
                if cost < ans:
                    ans = cost
    print(ans)
    return


if __name__ == "__main__":
    solve()

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

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

Solution (Python):
from itertools import permutations

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

cnt = [[0] * C for _ in range(3)]
for h in range(N):
    for w, c in enumerate(map(int, input().split())):
        cnt[(h + w) % 3][c - 1] += 1

ans = 10**18
for perm in permutations(range(C), r=3):
    cost = 0
    for c, ns in zip(perm, cnt):
        for fr in range(C):
            if fr == c:
                continue
            cost += D[fr][c] * ns[fr]
    ans = min(ans, cost)
print(ans)

Solution (Python):
from itertools import permutations

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

cnt = [[0] * C for _ in range(3)]
for h in range(N):
    for w, c in enumerate(map(int, input().split())):
        cnt[(h + w) % 3][c - 1] += 1

ans = 10**18
for perm in permutations(range(C), r=3):
    cost = 0
    for c, ns in zip(perm, cnt):
        for fr in range(C):
            if fr == c:
                continue
            cost += D[fr][c] * ns[fr]
    ans = min(ans, cost)
print(ans)

Solution (Python):
n,c=map(int,input().split())
d=[list(map(int,input().split())) for i in range(c)]
g=[list(map(int,input().split())) for i in range(n)]
mod0=set()
mod1=set()
mod2=set()
for i in range(n):
  for j in range(n):
    if (i+j+2)%3==0:
      mod0.add((i,j))
    elif (i+j+2)%3==1:
      mod1.add((i,j))
    else:
      mod2.add((i,j))
cost1=[0]*c
for c1 in range(c):
  tmp=0
  for y,x in mod0:
    tmp+=d[g[y][x]-1][c1]
  cost1[c1]+=tmp
cost2=[0]*c
for c2 in range(c):
  tmp=0
  for y,x in mod1:
    tmp+=d[g[y][x]-1][c2]
  cost2[c2]+=tmp
cost3=[0]*c
for c3 in range(c):
  tmp=0
  for y,x in mod2:
    tmp+=d[g[y][x]-1][c3]
  cost3[c3]+=tmp
ans=10**18
for c1 in range(c):
  for c2 in range(c):
    for c3 in range(c):
      if c1==c2 or c2==c3 or c3==c1:
        continue
      ans=min(ans,cost1[c1]+cost2[c2]+cost3[c3])
print(ans)

Solution (Python):

from collections import Counter
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, C1, C2 = [], [], []
for i in range(n):
    for j in range(n):
        if (i + j) % 3 == 0:
            C0.append(C[i][j]-1)
        elif (i + j) % 3 == 1:
            C1.append(C[i][j]-1)
        else:
            C2.append(C[i][j]-1)
C0 = Counter(C0)
C1 = Counter(C1)
C2 = Counter(C2)

ans = 10 ** 10
for i in range(c):
    for j in range(c):
        if i == j:
            continue
        for k in range(c):
            if i == k or j == k:
                continue
            tmp = 0
            for col, num in C0.items():
                tmp += D[col][i] * num
            for col, num in C1.items():
                tmp += D[col][j] * num
            for col, num in C2.items():
                tmp += D[col][k] * num
            
            ans = min(tmp, ans)
            
print(ans)

Solution (Python):
N, C = map(int, input().split())
D = []
for _ in range(C):
    D.append([int(d) for d in input().split()])
t = [[0 for _ in range(C)] for _ in range(3)]
for i in range(N):
    for j, c in enumerate(input().split()):
        c = int(c) - 1
        t[(i + j) % 3][c] += 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
            res = 0
            for l in range(C):
                res += D[l][i] * t[0][l]
                res += D[l][j] * t[1][l]
                res += D[l][k] * t[2][l]
            ans = min(ans, res)
print(ans)

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

n, c = [int(x) for x in input().split()]

d_list = [[int(x) for x in input().split()] for _ in range(c)]
c_ = [[int(x) for x in input().split()] for _ in range(n)]

mod_0 = [0] * c
mod_1 = [0] * c
mod_2 = [0] * c

for i in range(n):
    for j in range(n):
        if (i + j) % 3 == 0:
            m = mod_0
        elif (i + j) % 3 == 1:
            m = mod_1
        else:
            m = mod_2
        for k in range(c):
            m[k] += d_list[c_[i][j] - 1][k]

ans = 10 ** 18

for i in range(c):
    for j in range(i + 1, c):
        for k in range(j + 1, c):
            a = mod_0[i] + mod_1[j] + mod_2[k]
            b = mod_0[i] + mod_1[k] + mod_2[j]
            c__ = mod_0[j] + mod_1[i] + mod_2[k]
            d = mod_0[j] + mod_1[k] + mod_2[i]
            e = mod_0[k] + mod_1[i] + mod_2[j]
            f = mod_0[k] + mod_1[j] + mod_2[i]
            ans = min(ans, a, b, c__, d, e, f)

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)]
mod0 = []
mod1 = []
mod2 = []
for i in range(n):
    for j in range(n):
        
        if (i+j)%3 == 1:
            mod0.append(C[i][j]-1)
        elif (i+j)%3 == 2:
            mod1.append(C[i][j]-1)
        else:
            mod2.append(C[i][j]-1)

conv_0, conv_1, conv_2 = [],[],[]
for i in range(c):
    tmp0, tmp1, tmp2 = 0,0,0
    for j in range(len(mod0)):
        tmp0 += D[mod0[j]][i]
    for j in range(len(mod1)):
        tmp1 += D[mod1[j]][i]
    for j in range(len(mod2)):
        tmp2 += D[mod2[j]][i]
    conv_0.append(tmp0)
    conv_1.append(tmp1)
    conv_2.append(tmp2)
res = float('inf')
for x,y,z in itertools.permutations(list(range(c)), 3):
    cnt = conv_0[x] + conv_1[y] + conv_2[z]
    res = min(cnt, res)
print(res)

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)]
mod0 = []
mod1 = []
mod2 = []
for i in range(n):
    for j in range(n):
        
        if (i+j)%3 == 1:
            mod0.append(C[i][j]-1)
        elif (i+j)%3 == 2:
            mod1.append(C[i][j]-1)
        else:
            mod2.append(C[i][j]-1)

conv_0, conv_1, conv_2 = [],[],[]
for i in range(c):
    tmp0, tmp1, tmp2 = 0,0,0
    for j in range(len(mod0)):
        tmp0 += D[mod0[j]][i]
    for j in range(len(mod1)):
        tmp1 += D[mod1[j]][i]
    for j in range(len(mod2)):
        tmp2 += D[mod2[j]][i]
    conv_0.append(tmp0)
    conv_1.append(tmp1)
    conv_2.append(tmp2)
res = float('inf')
color_range = list(range(c))
for x,y,z in itertools.permutations(color_range, 3):
    cnt = 0
    cnt = conv_0[x] + conv_1[y] + conv_2[z]
    res = min(cnt, res)
print(res)

Solution (Python):
n, c = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
s = [list(map(int, input().split())) for _ in range(n)]
c0 = [[0 for _ in range(c)] for _ in range(3)]
c1 = [[0 for _ in range(c)] for _ in range(3)]
for i in range(n):
    for j in range(n):
        if (i + j) % 3 == 0:
            c0[0][s[i][j] - 1] += 1
        elif (i + j) % 3 == 1:
            c0[1][s[i][j] - 1] += 1
        elif (i + j) % 3 == 2:
            c0[2][s[i][j] - 1] += 1
for i in range(3):
    for j in range(c):
        for k in range(c):
            c1[i][j] += d[k][j] * c0[i][k]
"""
c2, c3 = [], []
for i in range(3):
    c2 = []
    for j in range(3):
        x = c1[i]
        a = [min(x), x.index(min(x))]
        c2.append(a)
        c1[i][c1[i].index(min(c1[i]))] = 10 ** 9
    c3.append(c2)
ans = 10 ** 9
for i in range(3):
    for j in range(3):
        for k in range(3):
            if c3[0][i][1] != c3[1][j][1] and c3[0][i][1] != c3[2][k][1] and c3[2][j][1] != c3[2][k][1]:
                m = c3[0][i][0] + c3[1][j][0] + c3[2][k][0]
                if m < ans:
                    ans = m
print(ans)"""
m = 0
ans = 10 ** 9
for i in range(c):
    for j in range(c):
        for k in range(c):
            if i != j and j != k and k != i:
                m = c1[0][i] + c1[1][j] + c1[2][k]
                if m < ans:
                    ans = m
print(ans)

Solution (Python):
from itertools import permutations

n,cn = map(int,input().split())
d = [list(map(int,input().split())) for _ in range(cn)]
c = [list(map(int,input().split())) for _ in range(n)]

col_count = [[0] * cn for _ in range(3)]
for i in range(n):
    for j in range(n):
        col_count[(i+j+2)%3][c[i][j]-1] += 1

ans = 1000*n*n
for c123 in permutations(range(cn),3):
    dsum = 0
    for i in range(3):
        for j in range(cn):
            dsum += d[j][c123[i]] * col_count[i][j]
    ans = min(ans,dsum)
print(ans)

Solution (Python):
from collections import Counter

N, C = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
grid = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]

group = [Counter() for _ in range(3)]
for i in range(N):
    for j in range(N):
        group[(i + j) % 3][grid[i][j]] += 1

ans = float('inf')
for c0 in range(C):
    for c1 in range(C):
        if c0 == c1:
            continue
        for c2 in range(C):
            if c2 == c0 or c2 == c1:
                continue
            cnt = 0
            color = [c0, c1, c2]
            for G, nc in zip(group, color):
                for c in list(G.keys()):
                    cnt += G[c] * D[c][nc]
            ans = min(ans, cnt)

print(ans)

Solution (Python):


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


col=[[0]*30 for i in range(3)]

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

ans=10**9
for col0 in range(C):
    temp0=0
    for i in range(C):
        temp0+=col[0][i]*D[i][col0] 
    for col1 in range(C):
        if col0==col1:
            continue
        
        temp1=temp0
        for i in range(C):
            temp1+=col[1][i]*D[i][col1]
        for col2 in range(C):
            if col2==col0 or col2==col1:
                continue
            temp2=temp1
            for i in range(C):
                
                temp2+=col[2][i]*D[i][col2]
            
            ans=min(ans,temp2)
            
print(ans)

Solution (Python):
import sys
input=sys.stdin.readline
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)]
ans=10**18
mod0=[]
mod1=[]
mod2=[]
for i in range(N):
  for j in range(N):
    k=(i+j+2)%3
    if k==0:
      mod0.append((i,j))
    elif k==1:
      mod1.append((i,j))
    else:
      mod2.append((i,j))
cnt0=[0]*(C+1)
cnt1=[0]*(C+1)
cnt2=[0]*(C+1)
for c0 in range(1,C+1):
  for x,y in mod0:
    cnt0[c0]+=d[c[x][y]-1][c0-1]
for c1 in range(1,C+1):
  for x,y in mod1:
    cnt1[c1]+=d[c[x][y]-1][c1-1]
for c2 in range(1,C+1):
  for x,y in mod2:
    cnt2[c2]+=d[c[x][y]-1][c2-1]
ans=10**18
for c0 in range(1,C+1):
  for c1 in range(1,C+1):
    for c2 in range(1,C+1):
      if c1==c2 or c2==c0 or c0==c1:
        continue
      cnt=cnt0[c0]+cnt1[c1]+cnt2[c2]
      ans=min(ans,cnt)
print(ans)

Solution (Python):




import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    




from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations








N, C = read_ints()
D = read_matrix(C)





Cmap = read_matrix(N)

if N == 1:
    print(0)
    exit()

lsbymod = defaultdict(lambda: defaultdict(lambda: 0))
for i in range(N):
    for j in range(N):
        lsbymod[(i + j + 2) % 3][Cmap[i][j] - 1] += 1








def ret_score(*arg):
    
    ret = 0
    for i in range(3):
        for k, v in lsbymod[i].items():
            ret += v * D[k][arg[i]]
    return ret


ans = 2**63
for a, b, c in permutations(range(C), 3):
    
    ans = min(ans, ret_score(a, b, c))

print(ans)

Solution (Python):




import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    




from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations








N, C = read_ints()
D = read_matrix(C)





Cmap = read_matrix(N)

if N == 1:
    print(0)
    exit()

lsbymod = defaultdict(lambda: [])
for i in range(N):
    for j in range(N):
        lsbymod[(i + j + 2) % 3].append(Cmap[i][j] - 1)


for k, v in lsbymod.items():
    lsbymod[k] = Counter(v)








def ret_score(*arg):
    
    ret = 0
    for i in range(3):
        for k, v in lsbymod[i].items():
            ret += v * D[k][arg[i]]
    return ret


ans = 2**63
for a, b, c in permutations(range(C), 3):
    
    ans = min(ans, ret_score(a, b, c))

print(ans)

Solution (Python):




import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    




from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations








N, C = read_ints()
D = read_matrix(C)





Cmap = read_matrix(N)

if N == 1:
    print(0)
    exit()

lsbymod = defaultdict(lambda: [])
for i in range(N):
    for j in range(N):
        lsbymod[(i + j + 2) % 3].append(Cmap[i][j] - 1)


for k, v in lsbymod.items():
    lsbymod[k] = Counter(v)








def ret_score(*arg):
    
    ret = 0
    for i in range(3):
        for k, v in lsbymod[i].items():
            ret += v * D[k][arg[i]]
    return ret


ans = 2**63
for a, b, c in permutations(range(C), 3):
    
    ans = min(ans, ret_score(a, b, c))

print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
from itertools import product
INF = 10**9
MOD = 10**9 + 7

def main():
    n,c = map(int,input().split())
    D = [list(map(int,input().split())) for _ in range(c)]
    grid0 = []
    grid1 = []
    grid2 = []
    for i in range(n):
        g = [int(i)-1 for i in input().split()]
        for j in range(n):
            if  (i+j)%3 == 0:
                grid0.append(g[j])
            elif (i+j)%3 == 1:
                grid1.append(g[j])
            else:
                grid2.append(g[j])
        
    
    def drew(grid):
        ans = [[INF,-2] for _ in range(3)] 
        for i in range(c):
            t = 0
            for g in grid:
                t += D[g][i]
            if t < ans[0][0]:
                ans[2] = ans[1]
                ans[1] = ans[0]
                ans[0] = [t,i]
            elif t < ans[1][0]:
                ans[2] = ans[1]
                ans[1] = [t,i]
            elif t < ans[2][0]:
                ans[2] = [t,i]

        return ans
    
    a = drew(grid0)
    b = drew(grid1)
    c = drew(grid2)
    ans = INF 
    for x,y,z in product(a,b,c):
        if  x[1] != y[1] and y[1] != z[1] and z[1] != x[1]:
            ans = min(ans,x[0]+y[0]+z[0])
    
    print(ans)
   
if __name__=='__main__':
    main()

Solution (Python):
import sys
import math
mod=10**9+7
inf=float("inf")
from math import sqrt
from collections import deque
from collections import Counter
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)
from functools import lru_cache




n,c=map(int,input().split())
D=[]
for i in range(c):
    D.append(list(map(int,input().split())))
G=[]
for i in range(n):
    a=list(map(int,input().split()))
    G.append([i-1 for i in a])
A=[]
B=[]
C=[]
for i in range(n):
    for j in range(n):
        d=(i+j)%3
        if d==0:
            A.append(G[i][j])
        elif d==1:
            B.append(G[i][j])
        else:
            C.append(G[i][j])
A=Counter(A);B=Counter(B);C=Counter(C)
cost=inf
for s in range(c):
    for t in range(c):
        if s==t:continue
        for r in range(c):
            if s==r or t==r:continue
            cost=min(cost, sum(D[i][s]*j for i,j in A.items())+sum(D[i][t]*j for i,j in B.items())+sum(D[i][r]*j for i,j in C.items()))
print(cost)

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)]
color = [{} for i in range(3)]
for h in range(N):
    for w in range(N):
        if c[h][w] not in color[(h+w+2)%3]:
            color[(h+w+2)%3][c[h][w]] = 1
        else:
            color[(h+w+2)%3][c[h][w]] += 1

ans = float('inf')
for c1 in range(1,C+1):
    for c2 in range(1,C+1):
        if c1 != c2:
            for c3 in range(1,C+1):
                if c1 != c3 and c2 != c3:
                    cand = 0
                    for k,v in color[0].items():
                        cand += D[k-1][c1-1]*v
                    for k,v in color[1].items():
                        cand += D[k-1][c2-1]*v
                    for k,v in color[2].items():
                        cand += D[k-1][c3-1]*v
                    ans = min(ans,cand)
print(ans)

Solution (Python):
N, C = map(int, input().split())
D = [tuple(map(int, input().split())) for _ in range(C)]
color = [tuple(map(int, input().split())) for _ in range(N)]

wrongness = [[0, 0, 0] for _ in range(C)]

for c in range(C):
    for i in range(N):
        for j in range(N):
            wrongness[c][(i + j) % 3] += D[color[i][j] - 1][c]

ans = 10**18

for c1 in range(C):
    for c2 in range(C):
        for c3 in range(C):
            if c1 == c2 or c2 == c3 or c3 == c1:
                continue
            ans = min(ans, wrongness[c1][0] + wrongness[c2][1] + wrongness[c3][2])

print(ans)

Solution (Python):
import sys
def input():
    return sys.stdin.readline()[:-1]
N,C=map(int,input().split())
D=[tuple(map(int, input().split())) for i in range(C)]
c=[tuple(map(lambda x:int(x)-1, input().split())) for i in range(N)]
iw=[[0]*C for i in range(3)]
l=[[] for i in range(3)]
for i in range(N):
    for j in range(N):
        l[(i+j)%3].append(c[i][j])
for i in range(3):
    for j in range(C):
        for k in l[i]:
            iw[i][j]+=D[k][j]
a=10**9
for i in range(C):
    for j in range(C):
        for k in range(C):
            if i!=j and i!=k and j!=k:
                a=min(a,iw[0][i]+iw[1][j]+iw[2][k])
print(a)

Solution (Python):
n, c_max = map(int, input().split())
D = []
for _ in range(c_max):
    d = list(map(int, input().split()))
    D.append(d)
C = []
for _ in range(n):
    c = list(map(int, input().split()))
    C.append(c)

Res = [[] for _ in range(3)]
\
for i in range(n):
    for j in range(n):
        now = C[i][j]
        if (i+j) % 3 == 0:
            Res[0].append(now)
        elif (i+j) % 3 == 1:
            Res[1].append(now)
        else:
            Res[2].append(now)

Res_cost = [[0 for _ in range(c_max)] for _ in range(3)]

for i in range(3):    
    for color in range(c_max):
        cost = 0
        for now in Res[i]:
            cost += D[now-1][color-1]
        Res_cost[i][color-1] = cost

ans = 10**10
for i in range(c_max):
    for j in range(c_max):
        for k in range(c_max):
            if i == j or j == k or k == i:
                continue
            cost = Res_cost[0][i] + Res_cost[1][j] + Res_cost[2][k]
            ans = min(cost, ans)


print(ans)

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

Solution (Python):
from collections import Counter
from itertools import permutations

def main():
    N, C = map(int, input().split())
    D = tuple(tuple(map(int, input().split())) for _ in range(C))

    cnt = [Counter() for _ in range(3)]

    for i in range(N):
        c = [int(x)-1 for x in input().split()]
        for j in range(3):
            cnt[j].update(c[(3-(i+2)+j)%3::3])

    ans = 1000*500*500+5
    for p in permutations(range(C), 3):
        s = 0
        for j in range(3):
            s += sum(D[k][p[j]] * v for k, v in cnt[j].items())
        if s < ans: ans = s
    print(ans)

main()

Solution (Python):
from collections import Counter
from itertools import permutations

def main():
    N, C = map(int, input().split())
    D = [tuple(map(int, input().split())) for _ in range(C)]

    cnt = [Counter() for _ in range(3)]

    for i in range(N):
        c = [int(x)-1 for x in input().split()]
        for j in range(3):
            cnt[j].update(c[(3-(i+2)+j)%3::3])

    ans = 1000*500*500+5
    for p in permutations(range(C), 3):
        s = 0
        for j in range(3):
            s += sum(D[k][p[j]] * v for k, v in cnt[j].items())
        if s < ans: ans = s
    print(ans)

main()

Solution (Python):
from collections import Counter
from itertools import permutations

def main():
    N, C = map(int, input().split())
    D = [list(map(int, input().split())) for _ in range(C)]

    cnt = [Counter() for _ in range(3)]

    for i in range(N):
        c = [int(x)-1 for x in input().split()]
        for j in range(3):
            cnt[j].update(c[(3-(i+2)+j)%3::3])

    ans = 1000*500*500+5
    for p in permutations(range(C), 3):
        s = 0
        for j in range(3):
            s += sum(D[k][p[j]] * v for k, v in cnt[j].items())
        if s < ans: ans = s
    print(ans)

main()

Solution (Python):
from collections import Counter
from itertools import permutations

def main():
    N, C = map(int, input().split())
    D = [list(map(int, input().split())) for _ in range(C)]

    cnt = [Counter() for _ in range(3)]

    for i in range(N):
        c = [int(x)-1 for x in input().split()]
        for j in range(3):
            cnt[j].update(c[(3-(i+2)+j)%3::3])

    ans = 1000*500*500+5
    for p in permutations(range(C), 3):
        s = 0
        for j in range(3):
            s += sum(D[k][p[j]] * v for k, v in cnt[j].items())
        ans = min(ans, s)
    print(ans)

main()

Solution (Python):
from collections import Counter
from itertools import permutations

def main():
    N, C = map(int, input().split())
    D = [[int(x) for x in input().split()] for _ in range(C)]

    cnt = [Counter() for _ in range(3)]

    for i in range(N):
        c = [int(x)-1 for x in input().split()]
        for j in range(3):
            cnt[j].update(c[(3-(i+2)+j)%3::3])

    ans = 1000*500*500+5
    for p in permutations(range(C), 3):
        s = 0
        for j in range(3):
            s += sum(D[k][p[j]] * v for k, v in cnt[j].items())
        ans = min(ans, s)
    print(ans)

main()

Solution (Python):
from collections import Counter
from itertools import permutations

def main():
    N, C = map(int, input().split())
    D = [[int(x) for x in input().split()] for _ in range(C)]

    cnt = [Counter() for _ in range(3)]

    for i in range(N):
        c = [int(x)-1 for x in input().split()]
        for j in range(3):
            cnt[j].update(c[(3-(i+2)+j)%3::3])

    ans = 1000*500*500+5
    for p in permutations(range(C), 3):
        s = 0
        for j in range(3):
            for k, v in cnt[j].items():
                s += D[k][p[j]] * v
        ans = min(ans, s)

    print(ans)

main()

Solution (Python):
from collections import Counter
from itertools import permutations
import sys
input = sys.stdin.buffer.readline
N, C = map(int, input().split())
D = [[int(x) for x in input().split()] for _ in range(C)]

cnt = [Counter() for _ in range(3)]

for i in range(N):
    c = [int(x)-1 for x in input().split()]
    for j in range(3):
        cnt[j].update(c[(3-(i+2)+j)%3::3])

ans = 1000*500*500+5
for p in permutations(range(C), 3):
    s = 0
    for j in range(3):
        for k, v in cnt[j].items():
            s += D[k][p[j]] * v
    ans = min(ans, s)

print(ans)