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):
import numpy as np
import itertools
import sys
sys.setrecursionlimit(10**9)


INF=10**18
def solve(N,C,D,colormap,new_colormap):
    ans = INF
    for j in range(len(new_colormap)):
        new_colors = new_colormap[j]
        res = 0
        for mod in range(3):
            for current_color in range(1,C+1):
                if current_color == 0: continue
                new_color = new_colors[mod]
                res += D[current_color-1][new_color-1] * colormap[mod][current_color]

        ans = min(res,ans)

    
    print(ans)

    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    C = int(next(tokens))  
    D = [[int(next(tokens)) for _ in range(C)] for _ in range(C)]  
    c = [[int(next(tokens)) for _ in range(N)] for _ in range(N)]  


    colormap = np.zeros((3,C+1),dtype=int)
    for i in range(1,N+1):
        for j in range(1,N+1):
            k = i+j
            k %= 3
            colormap[k][c[i-1][j-1]] += 1
            

    new_color_comb = list(itertools.permutations(list(range(1,C+1)),3))
    solve(N, C, np.array(D), colormap, np.array(new_color_comb))



def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')

    
    cc.export('solve', '(i8,i8,i8[:,:],i8[:,:],i8[:,:],)')(solve)
    cc.compile()

if __name__ == '__main__':
    
    try:
        from my_module import solve
    except:
        cc_export()
        exit()

    main()

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

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

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 = defaultdict(lambda: defaultdict(int))

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

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
            
            cand = 0
            
            for k, v in cnt[0].items():
                cand += v*D[k][c1]
            
            for k, v in cnt[1].items():
                cand += v*D[k][c2]
            
            for k, v in cnt[2].items():
                cand += v*D[k][c3]
            
            ans = min(ans, cand)

print(ans)

Solution (Python):
import sys
import math
import copy
from heapq import heappush, heappop, heapify
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter



input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)

def solve():
    n, m = getList()
    g = []
    for i in range(m):
        g.append(getList())
    
    ll = [defaultdict(int) for i in range(3)]

    for i in range(n):
        l = getZList()
        for j, nn in enumerate(l):
            ll[(i+j) % 3][nn] += 1
    
    ans = INF
    for i in range(m):
        for j in range(m):
            if i == j:
                continue
            for k in range(m):
                if i == k or j == k:
                    continue
                tmp = 0
                for kk, vv in ll[0].items():
                    tmp += g[kk][i] * vv
                for kk, vv in ll[1].items():
                    tmp += g[kk][j] * vv
                for kk, vv in ll[2].items():
                    tmp += g[kk][k] * vv
                    
                
                ans = min(ans, tmp)

    print(ans)

def main():
    n = getN()
    for _ in range(n):
        solve()

    return
if __name__ == "__main__":
    
    solve()

Solution (Python):

n, c = map(int, input().split())
D = []
for i in range(c):
    new_line = list(map(int, input().split()))
    D.append(new_line)

C = []
for i in range(n):
    new_line = list(map(lambda x: int(x) - 1, input().split()))
    C.append(new_line)

color_list = [[], [], []]
for i in range(n):
    for j in range(n):
        mod = ((i + 1) + (j + 1)) % 3
        color = C[i][j]
        color_list[mod].append(color)

def change_color_cost(mod, change_color):
    target = color_list[mod]
    total = 0
    for base_color in target:
        total += D[base_color][change_color]
    return total


def top3(mod):
    min_costs = [[None, float("inf")]] * 3
    for color in range(c):
        cost = change_color_cost(mod, color)
        min_costs.append([color, cost])
        min_costs.sort(key=lambda x: x[1])
        min_costs = min_costs[:3]
    return min_costs


tops = []
for mod in range(3):
    tops.append(top3(mod))


min_cost = float("inf")
for color0, cost0 in tops[0]:
    for color1, cost1 in tops[1]:
        for color2, cost2 in tops[2]:
            if color0 != color1 and color1 != color2 and color2 != color0:
                min_cost = min(min_cost, cost0 + cost1 + cost2)
print(min_cost)

Solution (Python):
from itertools import permutations

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

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

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

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

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

INF = 10**9
ans = INF

for cols in permutations(range(C), 3):
  temp = 0
  for i, Y in enumerate(cols):
    for X, cnt in enumerate(color[i]):
      temp += D[X][Y] * cnt
  ans = min(ans, temp)

print(ans)

Solution (Python):
from itertools import permutations

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

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

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

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

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

INF = 10**9
ans = INF

for cols in permutations(range(C), 3):
  temp = 0
  for i, Y in enumerate(cols):
    for X, cnt in enumerate(color[i]):
      temp += D[X][Y] * cnt
  ans = min(ans, temp)

print(ans)

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 

from decimal import *



N, C = MAP()
D = [LIST() for _ in range(C)]
c = [LIST() for _ in range(N)]

c_kind = [[0]*(C+1) for _ in range(3)]

cost = [[0]*(C+1) for _ in range(3)]


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


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

ans = INF
for a, b, c in permutations(range(1, C+1), 3):
	ans = min(ans, cost[0][a]+cost[1][b]+cost[2][c])

print(ans)

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

Solution (Python):
from collections import defaultdict
import itertools

n, c = list(map(int, input().split()))

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

d = [defaultdict(int), defaultdict(int), defaultdict(int)]

for i in range(n):
    for j in range(n):
        r = (i + j) % 3
        d[r][C[i][j]] += 1

cost = [[0] * c for _ in range(3)]

for i in range(3):
    dic = d[i]
    for j in range(c):
        for k, v in dic.items():
            cost[i][j-1] += v * D[k-1][j-1]

ans = 1e9

for i, j, k in itertools.permutations(range(c), 3):
    ans = min(cost[0][i] + cost[1][j] + cost[2][k], ans)

print(ans)

Solution (Python):
import sys
from itertools import permutations

input = sys.stdin.readline


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

    R = [[0] * C for _ in range(3)]
    for i in range(N):
        for j in range(N):
            R[(i + j + 2) % 3][A[i][j] - 1] += 1

    cost = [[0] * C for _ in range(3)]
    for r in range(3):
        for Y in range(C):
            tmp = 0
            for X, num in enumerate(R[r]):
                tmp += D[X][Y] * num
            cost[r][Y] = tmp

    ans = float("inf")
    for c0, c1, c2 in permutations(range(C), r=3):
        ans = min(ans, cost[0][c0] + cost[1][c1] + cost[2][c2])

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import sys
from itertools import permutations

input = sys.stdin.readline


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

    R = [[0] * C for _ in range(3)]
    for i in range(N):
        for j in range(N):
            R[(i + j + 2) % 3][A[i][j] - 1] += 1

    cost = [[0] * C for _ in range(3)]
    for r in range(3):
        for Y in range(C):
            tmp = 0
            for X, num in enumerate(R[r]):
                tmp += D[X][Y] * num
            cost[r][Y] = tmp

    ans = float("inf")
    for c0, c1, c2 in permutations(range(C), r=3):
        ans = min(ans, cost[0][c0] + cost[1][c1] + cost[2][c2])

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
n,c=map(int,input().split())

C0={i:0 for i in range(1,c+1)}
C1={i:0 for i in range(1,c+1)}
C2={i:0 for i in range(1,c+1)}

CH=[-1]
for i in range(c):
    new=[-1]+[int(i) for i in input().split()]
    CH.append(new[:])

for i in range(n):
    D=[int(i) for i in input().split()]
    for q in range(n):
        now=(i+q)%3
        if now==0:
            C0[D[q]]+=1
        elif now==1:
            C1[D[q]]+=1
        else:
            C2[D[q]]+=1



def calc(dic,col):
    res=0
    for ele in dic:
        res+=dic[ele]*CH[ele][col]
    return res

ans=10**10
for i in range(1,c+1):
    for q in range(1,c+1):
        for r in range(1,c+1):
            if i==q or q==r or r==i:
                continue
            sub=0
            sub+=calc(C0,i)
            sub+=calc(C1,q)
            sub+=calc(C2,r)
            ans=min(ans,sub)

print(ans)

Solution (Python):


from itertools import permutations

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

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


colors = [[0]*C for i in range(3)]
for i in range(N):
    tmp = list(map(int, input().split()))
    for j, color in enumerate(tmp):
        num = ((i+1) + (j+1)) % 3
        colors[num][color-1] += 1


data = [[0]*C for i in range(3)]


for i in range(3):
    
    for j in range(C):
        for k in range(C):
            data[i][k] += colors[i][j] * D[j][k]


ans = 10**10
for iter_ in permutations(list(range(C)), 3):
    
    tmp = []
    for i, j in enumerate(iter_):
        tmp.append(data[i][j])
    ans = min(ans, sum(tmp))
print(ans)

Solution (Python):
LI = lambda: list(map(int, input().split()))

N, C = LI()
D = [LI() for _ in range(C)]
c = [LI() for _ in range(N)]

INF = 10 ** 15


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


if __name__ == "__main__":
    main()

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

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

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


def main():
    N, C = map(int, readline().split())
    D = [0] * C
    for i in range(C):
        D[i] = list(map(int, readline().split()))
    G = [0] * N
    for i in range(N):
        G[i] = [int(s) - 1 for s in readline().split()]

    counter = [[0] * C for _ in range(3)]
    cost = [[0] * C for _ in range(3)]
    for x in range(N):
        for y in range(N):
            counter[(x + y) % 3][G[x][y]] += 1

    for cur_cost, cur_counter in zip(cost, counter):
        for i in range(C):
            for j in range(C):
                cur_cost[i] += cur_counter[j] * D[j][i]

    ans = INF
    for c1, c2, c3 in permutations(range(C), 3):
        if ans > cost[0][c1] + cost[1][c2] + cost[2][c3]:
            ans = cost[0][c1] + cost[1][c2] + cost[2][c3]

    print(ans)
    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from itertools import permutations

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


def main():
    N, C = map(int, readline().split())
    D = [0] * C
    for i in range(C):
        D[i] = list(map(int, readline().split()))
    G = [0] * N
    for i in range(N):
        G[i] = [int(s) - 1 for s in readline().split()]

    cost = [[0] * C for _ in range(3)]
    for x in range(N):
        for y in range(N):
            color = G[x][y]
            cost_current = cost[(x + y) % 3]
            for i in range(C):
                cost_current[i] += D[color][i]

    ans = INF
    for c1, c2, c3 in permutations(range(C), 3):
        if ans > cost[0][c1] + cost[1][c2] + cost[2][c3]:
            ans = cost[0][c1] + cost[1][c2] + cost[2][c3]

    print(ans)
    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from itertools import permutations

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


def main():
    N, C = map(int, readline().split())
    D = [0] * C
    for i in range(C):
        D[i] = list(map(int, readline().split()))
    G = [0] * N
    for i in range(N):
        G[i] = [int(s) - 1 for s in readline().split()]

    cost = [[0] * C for _ in range(3)]
    for x in range(N):
        for y in range(N):
            color = G[x][y]
            cost_current = cost[(x + y) % 3]
            for i in range(C):
                cost_current[i] += D[color][i]

    ans = INF
    for c1, c2, c3 in permutations(range(C), 3):
        if ans > cost[0][c1] + cost[1][c2] + cost[2][c3]:
            ans = cost[0][c1] + cost[1][c2] + cost[2][c3]

    print(ans)
    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys
import math
import collections
import bisect
import copy
import itertools



sys.setrecursionlimit(10 ** 7)
INF = 10 ** 16
MOD = 10 ** 9 + 7


ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))





def main():
    n, c = ns()
    d = [na() for _ in range(c)]
    color = [na() for _ in range(n)]

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

    for i in range(n):
        for j in range(n):
            cnt[(i + j) % 3][color[i][j] - 1] += 1

    ans = INF
    for cost in itertools.permutations(range(c), 3):
        tmp_ans = 0
        for i in range(3):
            for j in range(c):
                tmp_ans += cnt[i][j] * d[j][cost[i]]
        ans = min(ans, tmp_ans)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
from collections import defaultdict
N, C = map(int, input().split())
D = [[int(i) for i in input().split()] for _ in range(C)]

color = [[int(i) for i in input().split()] for _ in range(N)]
M = [defaultdict(int) for _ in range(3)]
for i in range(N):
    for j in range(N):
        M[(i+j) % 3][color[i][j]] += 1

ans = 10**20
for Y0 in range(C):
    for Y1 in range(C):
        for Y2 in range(C):
            if Y0 != Y1 and Y1 != Y2 and Y2 != Y0:
                Y = (Y0, Y1, Y2)
                d = 0
                for i in range(3):
                    for X, v in M[i].items():
                        d += D[X-1][Y[i]]*v
                ans = min(ans, d)
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)]

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

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)]
ci = [[] for _ in range(3)]
for i in range(n):
    cl = list(map(int, input().split()))
    for j in range(3):
        ci[(i+j)%3].extend(cl[j::3])
for i in range(3):
    ci[i] = Counter(ci[i])

def iwa(cols):
    ret = 0
    for i in range(3):
        for x, v in ci[i].items():
            ret += v * d[x-1][cols[i]]
    return ret

L = list(permutations(range(c), 3))
ret = 500*500*1000
for cols in L:
    ret = min(ret, iwa(cols))
print(ret)

Solution (Python):
N,C=(int(i) for i in input().strip().split(" "))
D=[]
c=[]
for i in range(C):
    D.append([int(i) for i in input().strip().split(" ")])
for i in range(N):
    c.append([int(i) for i in input().strip().split(" ")])
from collections import defaultdict
d0=defaultdict(int)
d1=defaultdict(int)
d2=defaultdict(int)
d=[d0,d1,d2]
for i in range(N):
    for j in range(N):
        d[(i+j+2)%3][c[i][j]]+=1

from itertools import permutations
l=list(range(1,C+1))
k=permutations(l,3)
m=999999999999999999999999
for p in k:
    w=0
    a0,a1,a2=p
    for i in d[0].keys():
        w+=(D[i-1][a0-1]*(d[0][i]))
    for i in d[1].keys():
        w+=(D[i-1][a1-1]*(d[1][i]))
    for i in d[2].keys():
        w+=(D[i-1][a2-1]*(d[2][i]))
    if w<m:
        m=w
print(m)

Solution (Python):
from itertools import permutations

n,c = map(int, input().split())
cln = list(range(0,c))
cpl = list(permutations(cln,3))

dl = []
for _ in range(c):
    row = list(map(int, input().split()))
    dl.append(row)

cl = []
for _ in range(n):
    row = list(map(int, input().split()))
    cl.append(row)


costs = [ [0]*c for _ in range(3) ]
for i in range(n):
    for j in range(n):
        for target_c in range(c):
            val3 = (i+j+2)%3
            orig_c = cl[i][j]-1
            cost = dl[orig_c][target_c]
            costs[val3][target_c] += cost


ans = 10**10
for cp in cpl:
    cost = costs[0][cp[0]] + costs[1][cp[1]] + costs[2][cp[2]]
    ans = min(ans,cost)

print(ans)

Solution (Python):
n,c = map(int,input().split())

D_list = [[int(i) for i in input().split()] for _ in range(c)]
c_list = [[int(i) for i in input().split()] for _ in range(n)]

c_num=[[0 for _ in range(3)] for __ in range(c)]

for a in range(n):
    for b in range(n):
        c_num[c_list[b][a]-1][(a+b+2)%3] += 1


ans = 10 ** 10
for i in range(1,c**3):
    x=i%c
    y=(i%c**2)//c
    z=i//c**2
    if x==y or y==z or z==x:
        continue
    else:
        color=[x,y,z]
        count = 0
        for s in range(3):
            for t in range(c):
                count += c_num[t][s] *D_list[t][color[s]]

        if count < ans:
            ans = count

print(ans)

Solution (Python):
from itertools import permutations

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

D = [None] * C
for i in range(C):
    D[i] = list(map(int, input().split()))

c = [None] * N
for i in range(N):
    c[i] = list(map(int, input().split()))


t = [[0]*C for _ in range(3)]
for i in range(N):
    for j in range(N):
        t[(i+j)%3][c[i][j]-1] += 1

ans = 10**12


for p in permutations(range(C),3):
    tmp = 0
    for i in range(C):
        tmp += D[i][p[0]] * t[0][i]
        tmp += D[i][p[1]] * t[1][i]
        tmp += D[i][p[2]] * t[2][i]
    ans = min(ans,tmp)

print(ans)

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

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

ans = float('inf')
from itertools import permutations
for ptn in permutations(range(1,C+1), 3):
    t = 0
    for p,c in zip(ptn,ctrs):
        for k,v in c.items():
            t += D[k-1][p-1] * v
    ans = min(ans, t)
print(ans)

Solution (Python):
'''
自宅用PCでの解答
'''
import math

import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit


ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
alp = "abcdefghijklmnopqrstuvwxyz"

def main():
    n,c = map(int,ipt().split())
    d = [[int(i) for i in ipt().split()] for j in range(c)]
    cs = [[int(i) for i in ipt().split()] for j in range(n)]
    di = [defaultdict(int) for i in range(3)]
    for i in range(n):
        for j in range(n):
            di[(i+j)%3][cs[i][j]] += 1

    cost = [[0]*c for i in range(3)]
    for i in range(3):
        for j in range(c):
            sm = 0
            for k in range(c):
                sm += d[k][j]*di[i][k+1]
            cost[i][j] = sm

    cm = [[(ci,i) for i,ci in enumerate(cost[j])] for j in range(3)]
    cm[0].sort()
    cm[1].sort()
    cm[2].sort()
    mi = 10**18
    for i in range(3):
        for j in range(3):
            for k in range(3):
                nm = cm[0][i][0]+cm[1][j][0]+cm[2][k][0]
                if cm[0][i][1] != cm[1][j][1] != cm[2][k][1] != cm[0][i][1] and mi > nm:
                    mi = nm

    print(mi)


    return None

if __name__ == '__main__':
    main()

Solution (Python):


import math

import itertools
from collections import deque
from collections import Counter
import heapq
from fractions  import gcd



n,m=map(int,input().split())
d=[list(map(int,input().split())) for _ in range(m)]
c_0={}
c_1={}
c_2={}

for i in range(n):
    c=list(map(int,input().split()))
    for j in range(n):
        if (i+j+2)%3==0:
            if c[j] not in c_0:
                c_0[c[j]]=1
            else:
                c_0[c[j]]+=1
        elif (i+j+2)%3==1:
            if c[j] not in c_1:
                c_1[c[j]]=1
            else:
                c_1[c[j]]+=1
        else:
            if c[j] not in c_2:
                c_2[c[j]]=1
            else:
                c_2[c[j]]+=1
color=[i for i in (range(1,m+1))]
ans=10**9
for l in itertools.permutations(color,3):
    x,y,z=l
    res=0
    for cr in c_0:
        res+=d[cr-1][x-1]*c_0[cr]
    for cr in c_1:
        res+=d[cr-1][y-1]*c_1[cr]
    for cr in c_2:
        res+=d[cr-1][z-1]*c_2[cr]
    ans=min(ans,res)
print(ans)

Solution (Python):
n,c = map(int, input().split())

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

ax = [[0 for i in range(c)] for j in range(3)]

for i in range(n):
    for j in range(n):
        x = (i+j) % 3
        ax[x][nl[i][j]-1] += 1

l = list(range(0,c))
import itertools
ll = list(itertools.permutations(l, 3))
res = float('inf')


for i in ll:
    temp= 0
    for j in range(c):
        temp += ax[0][j]*dl[j][i[0]]
        temp += ax[1][j]*dl[j][i[1]]
        temp += ax[2][j]*dl[j][i[2]]
    res= min(res,temp)
print(res)

Solution (Python):
import sys
import math
from collections import deque
from itertools import permutations

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


def main():
    N, C = NMI()
    D = [NLI() for _ in range(C)]
    grid = [list(map(lambda x: int(x)-1, NMI())) for _ in range(N)]

    grid_mod = [{i:0 for i in range(C)} for _ in range(3)]
    for h in range(N):
        for w in range(N):
            t = (h+w) % 3
            grid_mod[t][grid[h][w]] += 1

    ans = 10**10
    for colors in permutations(range(C), 3):
        diff = 0
        for i in range(3):
            for c, n in grid_mod[i].items():
                diff += D[c][colors[i]] * n
        ans = min(ans, diff)

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import itertools

N,C =map(int,input().split())
D = [0]+[[0]+list(map(int,input().split())) for i in range(C)]
c = [list(map(int,input().split())) for i in range(N)]
 
grid = [[],[],[]]
for i in range(N):
  for j in range(N):
    grid[(i+j)%3].append(c[i][j])

s = [[0]*(C+1) for i in range(3)]
 
for i in range(3):
  for j in range(1,C+1,1):
    for k in range(len(grid[i])):
      s[i][j]+=D[grid[i][k]][j]

ans = float("inf")
for p in itertools.permutations(list(range(1,C+1)),3):
  tmp = 0
  for i in range(3):
     tmp +=s[i][p[i]]
  ans = min(tmp,ans)

print(ans)

Solution (Python):
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


import sys
def query(i,j):
    print("? {0} {1}".format(i, j))
    sys.stdout.flush()
    return int(input())

n,c = list(map(int, input().split()))
ds = [None]*c
cs = [None]*n
for i in range(c):
    ds[i] = list(map(int, input().split()))
for i in range(n):
    cs[i] = list(map(lambda x : int(x)-1, input().split()))
from itertools import product
ans = float("inf")
v0 = [0]*c
v1 = [0]*c
v2 = [0]*c
for i,j in product(range(n), range(n)):
    if (i+j)%3==0:
        v = v0
    elif (i+j)%3==1:
        v = v1
    else:
        v = v2
    for cc in range(c):
        v[cc] += ds[cs[i][j]][cc]
for c0,c1,c2 in product(range(c), range(c), range(c)):
    if c0==c1 or c0==c2 or c1==c2:
        continue
    val = v0[c0] + v1[c1] + v2[c2]
    ans = min(ans, val)
print(ans)

Solution (Python):
import sys
from itertools import permutations

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


def resolve():
    n, c = map(int, input().split())
    D = [list(map(int, input().split())) for _ in range(c)]
    grid = [list(map(int, input().split())) for _ in range(n)]

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

    res = f_inf
    for pattern in permutations(list(range(c)), 3):
        cost = 0
        for idx, col in enumerate(pattern):
            for k in range(c):
                cnt = col_cnt[idx][k]
                cost += D[k][col] * cnt
        res = min(res, cost)
    print(res)


if __name__ == '__main__':
    resolve()