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

"""
問題：
条件を満たすようにc色の色を塗り替える場合に生じるコスト(違和感)
を最小化する。
条件：
ある任意の２箇所のグリッド grid[a][b]とgrid[c][d]を見た時に、
(a+b)%3 == (c+d)%3 ならば、その２箇所は同じ色である必要があり、
そうでない場合は違う色である必要がある。
6*6のグラフで見るとこんな感じになる
012012
120120
201201
012012
120120
201201 

解法：
色が30色であるという制約から、
30C3通りを試した時のコストの最小値が答えになる。
500*500のgridで高速に計算する必要があるため、
予めdictを用いて3で割った余りが0,1,2の場所に何の色が何個入っているか
を求めておき、あとはそれぞれの場所から変更先の色へのコストを求めれば
良い。
"""
import sys
from collections import defaultdict
import itertools
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

n,c = map(int,readline().split()) 
D = [] 

for i in range(c):
    D.append(list(map(int,readline().split())))

grid = [] 
for i in range(n):
    grid.append(list(map(int,readline().split())))



dic_0 = defaultdict(int)
dic_1 = defaultdict(int)
dic_2 = defaultdict(int)

for i in range(n):
    for j in range(n):
        if (i+j)%3 == 0:
            dic_0[grid[i][j]] += 1
        elif (i+j)%3 == 1:
            dic_1[grid[i][j]] += 1
        else:
            dic_2[grid[i][j]] += 1

colors = [i for i in range(1,c+1)]
ans = 10**9
for i,j,k in itertools.combinations(colors,3):
    for o,p,q in itertools.permutations([i,j,k]):
        res = 0
        for a,b in dic_0.items():
            res += D[a-1][o-1]*b
        for a,b in dic_1.items():
            res += D[a-1][p-1]*b
        for a,b in dic_2.items():
            res += D[a-1][q-1]*b

        ans = min(ans,res)

print(ans)

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

a = [[0]*c for _ in range(3)]
b = [[[0,i] for i in range(c)] for _ in range(3)]

for i in range(n):
  l = list(map(int,input().split()))
  for j in range(n):
    a[(i+j)%3][l[j]-1] += 1
    
for i in range(3):
  for k in range(c):
    b[i][k][0] = sum([a[i][t]*d[t][k] for t in range(c)])
p = [[],[],[]]
for i in range(3):
  p[i] = sorted(b[i])[:3]
m = []
for t in p[0]:
  for s in p[1]:
    for u in p[2]:
      if (t[1] != s[1]) and (t[1] != u[1]) and (s[1] != u[1]):
        m.append(t[0]+s[0]+u[0])
print(min(m))

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil
    

    
    

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

    for i in range(N):
        for j in range(N):
            amari = (i+j+2) % 3
            color = c[i][j]
            for k in range(C):
                iwakan[amari][k] += d[color-1][k]
    
    res = 10**20
    for i in permutations(range(C), 3):
        res = min(res, iwakan[0][i[0]]+iwakan[1][i[1]]+iwakan[2][i[2]])
    print(res)

if __name__ == '__main__':
    main()

Solution (Python):
n,c = map(int,input().split())
d = [[int(i) for i in input().split()] for _ in range(c)]
lc = [[int(i)-1 for i in input().split()] for _ in range(n)]

ans = float("inf")

dp = [[0] * c for i in range(3)]
for C in range(c):
  for y in range(n):
    for x in range(n):
      if lc[y][x] != c:
        dp[(y+x)%3][C] += d[lc[y][x]][C]
for c0 in range(c):
  for c1 in range(c):
    if c0 == c1: continue
    for c2 in range(c):
      if c0 == c2 or c1 == c2: continue
      ans = min(ans, dp[0][c0] + dp[1][c1] + dp[2][c2])
print(ans)

Solution (Python):
def main():
    N, C = map(int, input().split())
    D = []
    for _ in range(C):
        d = list(map(int, input().split()))
        D.append(d)
    c = []
    for _ in range(N):
        cc = list(map(int, input().split()))
        c.append(cc)
    l = [[0] * (C+1) for _ in range(3)]
    for i in range(N):
        for j in range(N):
            l[(i + j) % 3][c[i][j]] += 1
    m = pow(10, 10000)
    for i in range(1, C+1):
        for j in range(1, C+1):
            for k in range(1, C+1):
                if i == j or i == k or j == k:
                    continue
                t = 0
                for ii in range(1, C+1):
                    t += l[0][ii] * D[ii-1][i-1]
                for jj in range(1, C+1):
                    t += l[1][jj] * D[jj-1][j-1]
                for kk in range(1, C+1):
                    t += l[2][kk] * D[kk-1][k-1]
                m = min(m, t)
    print(m)
main()

Solution (Python):
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(int, input().split())) for _ in range(N)]
    T = [[0] * C for _ in range(3)]
    for x, y in product(range(N), repeat=2):
        r = (x + y) % 3
        for i in range(C):
            T[r][i] += D[c[x][y] - 1][i]
    Q = []
    for j in range(3):
        Q.append(sorted((t, i) for i, t in enumerate(T[j])))
    m = 10**10
    for x, y, z in product(range(3), repeat=3):
        X, Y, Z = Q[0][x], Q[1][y], Q[2][z]
        if X[1] == Y[1] or Y[1] == Z[1] or Z[1] == X[1]:
            continue
        m = min(m, X[0] + Y[0] + Z[0])
    return m


print(main())

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

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

co = [Counter() for i in range(3)]
for i in range(n):
    C = list(map(int,input().split()))
    for j in range(n):
        co[(i+j)%3][C[j]-1] +=1
ans = 10**15
perm = permutations([i for i in range(c)],3)

for t in perm:
    temp = 0
    for i in range(3):
        color = t[i]
        for num,cnt in co[i].items():
            temp += D[num][color] * cnt
    ans = min(temp,ans)
print(ans)

Solution (Python):
def main():
    from itertools import permutations

    N, C = map(int, input().split())
    change_cost = [[int(x) for x in input().split()] for _ in range(C)]
    init_color = [[int(x) - 1 for x in input().split()] for _ in range(N)]

    ctr = [[0] * C for _ in range(3)]
    for r in range(N):
        for c in range(N):
            p = (r + c) % 3
            color = init_color[r][c]
            ctr[p][color] += 1

    mi = 1000 * 500 * 500 + 1
    for perm in permutations(range(C), r=3):
        it = iter(perm)
        t = 0
        for p in range(3):
            color_to_be = next(it)
            for color, count in enumerate(ctr[p]):
                t += change_cost[color][color_to_be] * count
        mi = min(mi, t)
    print(mi)


if __name__ == '__main__':
    main()

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

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

    sup0 = [0] * C
    sup1 = [0] * C
    sup2 = [0] * C
    for i in range(N):
        for j in range(N):
            if (i + j) % 3 == 0:
                sup2[grid[i][j] - 1] += 1
            elif (i + j) % 3 == 1:
                sup0[grid[i][j] - 1] += 1
            elif (i + j) % 3 == 2:
                sup1[grid[i][j] - 1] += 1

    ans = 10 ** 18
    for i, j, k in permutations(range(C), 3):
        tmp = 0
        for c in range(C):
            tmp += D[c][i] * sup0[c]
            tmp += D[c][j] * sup1[c]
            tmp += D[c][k] * sup2[c]
        ans = min(ans, tmp)
    print(ans)

if __name__ == '__main__':
    main()

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

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

a = []
b = []

for _ in range(c):
    array = list(map(int, input().split()))
    a.append(array)

for _ in range(n):
    array = list(map(int, input().split()))
    b.append(array)


group1 = []
group2 = []
group3 = []

for i in range(n):
    for j in range(n):
        if (i + j) % 3 == 0:
            group1.append(b[i][j])
        elif (i + j) % 3 == 1:
            group2.append(b[i][j])
        else:
            group3.append(b[i][j])

g1 = Counter(group1)
g2 = Counter(group2)
g3 = Counter(group3)

sum1 = []
sum2 = []
sum3 = []


def cal(l, output):
    for i in range(c):
        s = 0
        for j in l.items():
            s += a[j[0]-1][i-1] * j[1]
        output.append(s)


li = [g1, g2, g3]
li2 = [sum1, sum2, sum3]

for i in range(3):
    cal(li[i], li2[i])

cc = list(range(c))

min_sum = 10**10
for i, j, k in permutations(cc, 3):
    sum = sum1[i] + sum2[j] + sum3[k]
    if sum < min_sum:
        min_sum = sum

print(min_sum)

Solution (Python):

N,C = map(int,input().split())
ld = [[]]
for i in range(C):
  ld.append([0]+list(map(int,input().split())))
lc = [[]]  
for i in range(N):
  lc.append([0]+list(map(int,input().split())))


lmae = [[0 for i in range(C+1)] for j in range(3)]
for p in range(1,N+1):
  for q in range(1,N+1):
    for i in range(1,C+1):
      X = lc[p][q]
      Y = i
      lmae[(p+q)%3][i] += ld[X][Y]


lans = []
for i in range(1,C+1):
  for j in range(i+1,C+1):
    for k in range(j+1,C+1):
      for cc in [[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]]:
        ans = lmae[cc[0]][i]+lmae[cc[1]][j]+lmae[cc[2]][k]
        lans.append(ans)
print(min(lans))

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

D = [tuple(map(int, input().split())) for _ in [0]*C]
K = [tuple(map(int, input().split())) for _ in [0]*N]

T = [[0]*C for _ in [0]*3]

for i, _k in enumerate(K):
    for j, k in enumerate(_k):
        z = (i+j) % 3
        T[z][k-1] += 1

ans = float('inf')
for a, b, c in permutations(range(C), 3):
    cost = 0
    cost += sum(t*D[i][a] for i, t in enumerate(T[0]))
    cost += sum(t*D[i][b] for i, t in enumerate(T[1]))
    cost += sum(t*D[i][c] for i, t in enumerate(T[2]))
    ans = min(ans, cost)
print(ans)

Solution (Python):




























from collections import defaultdict
N,C=map(int,input().split())
D=defaultdict(int)
t=defaultdict(int)

for i in range(C):
    s=list(map(int,input().split()))
    for j in range(C):
        D[(i,j)]=s[j]
for i in range(N):
    s=list(map(int,input().split()))
    for j in range(N):
        t[((i+j)%3,s[j]-1)]+=1
ans=1<<30
for i in range(C):
    for j in range(C):
        for k in range(C):
            if i!=j!=k!=i:
                res=0
                for l in range(C):res+=D[(l,i)]*t[(0,l)]
                for l in range(C):res+=D[(l,j)]*t[(1,l)]
                for l in range(C):res+=D[(l,k)]*t[(2,l)]
                ans=min(ans,res)

                
print(ans)

Solution (Python):
import sys
from itertools import permutations, combinations

n, c = map(int, sys.stdin.readline().split())
d = [[int(x) for x in sys.stdin.readline().split()] for _ in range(c)]
grid = [[int(x) - 1 for x in sys.stdin.readline().split()] for _ in range(n)]

cost = [[0] * c for _ in range(3)]
for i in range(n):
  for j in range(n):
    k = (i + j) % 3
    for l in range(c):
      cost[k][l] += d[grid[i][j]][l]
  
def main():
  res = []
  for comb in combinations(range(c), 3):
    for i, j, k in permutations(comb):
      res.append(cost[0][i] + cost[1][j] + cost[2][k])
  print(min(res))

if __name__ == '__main__':
  main()

Solution (Python):
from collections import defaultdict
n,c = map(int,input().split())
d = [0]
for i in range(c):
    d.append([0] + list(map(int,input().split())))
li0 = []
li1 = []
li2 = []
for i in range(n):
    g = list(map(int,input().split()))
    for j in range(n):
        if (i + j) % 3 == 0:
            li0.append(g[j])
        if (i + j) % 3 == 1:
            li1.append(g[j])
        if (i + j) % 3 == 2:
            li2.append(g[j])
dic0 = defaultdict(int)
dic1 = defaultdict(int)
dic2 = defaultdict(int)
for i in li0:
    dic0[i] += 1
for i in li1:
    dic1[i] += 1
for i in li2:
    dic2[i] += 1 
ans = 1000000000
for i in range(1,c+1):
    for j in range(1,c+1):
        for k in range(1,c+1):
            if i == j or j == k or i == k:
                continue
            x = 0
            for color in range(1,c+1):
                x += dic0[color] * d[color][i]
                x += dic1[color] * d[color][j]
                x += dic2[color] * d[color][k]
            ans = min(x,ans) 
print(ans)

Solution (Python):
from itertools import permutations


def main():
    n, c = map(int, input().split())
    d = [[int(x) for x in input().split()] for _ in range(c)]
    g = [[int(x) - 1 for x in input().split()] for _ in range(n)]
    count = [{}, {}, {}]
    for i in range(n):
        for j in range(n):
            now = g[i][j]
            index = (i + j + 2) % 3
            if now in count[index % 3]:
                count[index % 3][now] += 1
            else:
                count[index % 3][now] = 1
    answer = float("inf")
    for color in permutations([i for i in range(c)], 3):
        now_answer = 0
        for i in range(3):
            for before_color, num in count[i].items():
                now_answer += d[before_color][color[i]] * num
        answer = min(answer, now_answer)
    print(answer)


if __name__ == '__main__':
    main()

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

def solve():
    ans0 = []
    ans1 = []
    ans2 = []
    for col in range(1, c_cnt + 1):
        res = 0
        for i in range(n):
            for j in range(n):
                if (i + j) % 3 == 0:
                    res += d[c[i][j] - 1][col - 1]
        ans0.append(res)

    for col in range(1, c_cnt + 1):
        res = 0
        for i in range(n):
            for j in range(n):
                if (i + j) % 3 == 1:
                    res += d[c[i][j] - 1][col - 1]
        ans1.append(res)

    for col in range(1, c_cnt + 1):
        res = 0
        for i in range(n):
            for j in range(n):
                if (i + j) % 3 == 2:
                    res += d[c[i][j] - 1][col - 1]
        ans2.append(res)
        
    return ans0, ans1, ans2

res = 10 ** 18
ans0, ans1, ans2 = solve()
for i0, num0 in enumerate(ans0):
    for i1, num1 in enumerate(ans1): 
        for i2, num2 in enumerate(ans2):
            if i0 != i1 and i1 != i2 and i2 != i0:
                res = min(num0 + num1 + num2, res)
print(res)

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

cst = [[0,0,0] for i in range(C)]

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

ans = 10**10

for i in range(C):
    for j in range(C):
        for k in range(C):
            if i == j or i == k or j == k:
                continue
            x = [i,j,k]
            a = 0
            for l in range(3):
                for m in range(C):
                    a += D[m][x[l]]*cst[m][l]
            ans = min(ans,a)

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

cst = [[0,0,0] for i in range(C)]

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

ans = 10**10

for i in range(C):
    for j in range(C):
        for k in range(C):
            if i == j or i == k or j == k:
                continue
            ans = min(ans,cst[i][0]+cst[j][1]+cst[k][2])

print(ans)

Solution (Python):
import sys
import collections
import itertools

input = sys.stdin.readline


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

    A = [[] for j in range(3)]

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

    one = collections.Counter(A[0])
    two = collections.Counter(A[1])
    three = collections.Counter(A[2])

    ans = float("inf")
    for x, y, z in itertools.permutations(range(C), 3):
        tmp = 0
        for k in one.keys():
            tmp += D[k - 1][x] * one[k]
        for k in two.keys():
            tmp += D[k - 1][y] * two[k]
        for k in three.keys():
            tmp += D[k - 1][z] * three[k]

        ans = min(ans, tmp)

    print(ans)




if __name__ == '__main__':
    main()

Solution (Python):
import itertools

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

counter = [[0 for i in range(cc)] for j in range(3)]
for i in range(n):
    for j in range(n):
        counter[(i+j)%3][c[i][j]-1] += 1

m = 250000000
for y in itertools.permutations(range(cc), 3):
    new = 0
    for i in range(3):
        for x in range(cc):
            new += counter[i][x-1]*d[x-1][y[i]]
    m = min(m, new)

print(m)

Solution (Python):

from itertools import permutations


def submit():
    n, c = map(int, input().split())
    d = [list(map(int, input().split())) for _ in range(c)]    
    color = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)]
    color_cnt = {i: {cl: 0 for cl in range(c)} for i in range(3)}

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

    ans = float('inf')
    for c0, c1, c2 in permutations(range(c), 3):
        t = 0
        for cl in range(c):
            t += color_cnt[0][cl] * d[cl][c0]
            t += color_cnt[1][cl] * d[cl][c1]
            t += color_cnt[2][cl] * d[cl][c2]
        if t < ans:
            ans = t
    print(ans)


submit()

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

counts = [defaultdict(int) for _ in range(3)]
for i in range(n):
    for j in range(n):
        counts[(i+j+2) % 3][c[i][j]-1] += 1

def calc_cost(dic, color):
    cost = 0
    for k, v in dic.items():
        cost += d[k][color] * v
    return cost

INF = 10**9
cost = INF
for colors in permutations(range(C), 3):
    tmp_cost = 0
    for i in range(3):
        tmp_cost += calc_cost(counts[i], colors[i])
    cost = min(cost, tmp_cost)
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)]
g=[[] for i in range(3)]
for i in range(n):
    for j in range(n):
        g[(i+j+2)%3].append(c_[i][j]-1)

'''
for i in range(c):
    for j in range(c):
        for k in range(c):
            d[i][j]=min(d[i][j],d[i][k]+d[k][j])
print(d)
'''
f=[[] for i in range(3)]
for i in range(3):
    for j in range(c):
        x=0
        for k in g[i]:
            x+=d[k][j]
        f[i].append((j,x))
    f[i]=sorted(f[i],key=lambda x:x[1])[:3]
ans=[]

for i in f[0]:
    for j in f[1]:
        for k in f[2]:
            if i[0]!=j[0] and k[0]!=j[0] and i[0]!=k[0]:
                
                
                ans.append(i[1]+j[1]+k[1])
print(min(ans))

Solution (Python):
n,c=map(int,input().split())
d=[list(map(int,input().split())) for i in range(c)]
c_=[list(map(int,input().split())) for i in range(n)]
g=[[] for i in range(3)]
for i in range(n):
    for j in range(n):
        g[(i+j+2)%3].append(c_[i][j]-1)

'''
for i in range(c):
    for j in range(c):
        for k in range(c):
            d[i][j]=min(d[i][j],d[i][k]+d[k][j])
print(d)
'''
f=[[] for i in range(3)]
for i in range(3):
    for j in range(c):
        x=0
        for k in g[i]:
            x+=d[k][j]
        f[i].append((j,x))
    f[i]=sorted(f[i],key=lambda x:x[1])[:3]
ans=[]

for i in f[0]:
    for j in f[1]:
        for k in f[2]:
            if i[0]!=j[0] and k[0]!=j[0] and i[0]!=k[0]:
                
                
                ans.append(i[1]+j[1]+k[1])
print(min(ans))

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

Dmat=[]
for i in range(C):
  array=list(map(int,input().split()))
  Dmat.append(array)


grid_list=[{},{},{}]
for i in range(N):
  array=list(map(int,input().split()))
  for j in range(N):
    c=array[j]-1    
    mod=(i+j)%3
    if c in grid_list[mod]:
      grid_list[mod][c]+=1
    else:
      grid_list[mod][c]=1


min_cost=10**9
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 c,num in grid_list[0].items():
        cost+=Dmat[c][i]*num
      for c,num in grid_list[1].items():
        cost+=Dmat[c][j]*num
      for c,num in grid_list[2].items():
        cost+=Dmat[c][k]*num
          
      if cost<min_cost:
        
        min_cost=cost
          
print(min_cost)

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

Dmat=[]
for i in range(C):
  array=list(map(int,input().split()))
  Dmat.append(array)


cmat=[]
for i in range(N):
  array=list(map(int,input().split()))
  cmat.append(array)

grid_list=[{},{},{}]
for i in range(N):
  for j in range(N):
    c=cmat[i][j]-1
    mod=(i+j)%3
    if c in grid_list[mod]:
      grid_list[mod][c]+=1
    else:
      grid_list[mod][c]=1


min_cost=10**9
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 c in grid_list[0]:
        num=grid_list[0][c]
        cost+=Dmat[c][i]*num
      for c in grid_list[1]:
        num=grid_list[1][c]
        cost+=Dmat[c][j]*num
      for c in grid_list[2]:
        num=grid_list[2][c]
        cost+=Dmat[c][k]*num
          
      if cost<min_cost:
        
        min_cost=cost
          
print(min_cost)

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


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


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

for i, naname in enumerate(diago):
    for color in range(1, C+1):
        for j, cell in enumerate(naname):
            diff[i][color] += D[j-1][color-1] * cell


candicate = []
for i in range(1, C+1):
    for j in range(1, C+1):
        for k in range(1, C+1):
            if i != j and j != k and k != i:
                candicate.append(diff[0][i]+diff[1][j]+diff[2][k])
print(min(candicate))

Solution (Python):


def main():
    n, nc = map(int, input().split())
    d = [list(map(int, input().split())) for i in range(nc)]
    c = [list(map(int, input().split())) for i in range(n)]

    cnt = [[0 for _ in range(nc)] for eta in range(3)]
    for i in range(n):
        for j in range(n):
            eta = (i + j) % 3
            cnt[eta][c[i][j] - 1] += 1

    iwamin = 10 ** 9
    for c1 in range(nc):
        for c2 in range(nc):
            for c3 in range(nc):
                if len(set([c1, c2, c3])) < 3:
                    continue
                iwa = 0
                for c4 in range(nc):
                    iwa += cnt[0][c4] * d[c4][c1]
                    iwa += cnt[1][c4] * d[c4][c2]
                    iwa += cnt[2][c4] * d[c4][c3]
                iwamin = min(iwamin, iwa)
    print(iwamin)

if __name__ == "__main__":
    main()

Solution (Python):
import itertools

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

indices = [2, 0, 1]
count_color = [[0] * C for i in range(3)]
for i in range(N):
  idx = indices[i%3]
  for j in range(N):
    count_color[idx][c[i][j]-1] += 1
    idx = (idx + 1) % 3
    

ans = float('inf')
correspondence = list(itertools.permutations(range(C), 3))

for corr in correspondence:
  cost = 0
  for idx in range(3): 
    for color in range(C):
      cost += count_color[idx][color] * D[color][corr[idx]]
  ans = min(ans, cost)

print(ans)

Solution (Python):
import itertools as it
n,c= map(int,input().split())
dtab = []
dtab.append([0 for _ in range(c+1)])
for i in range(c):dtab.append([0] + list(map(int,input().split())))
ctab = []
ctab.append([0 for _ in range(n+1)])
for i in range(n):ctab.append([0]+list(map(int,input().split())))
ssd = [{},{},{}]
for i in range(1,n+1):
    for j in range(1,n+1):
        temp = (i+j)%3
        temp2 = ctab[i][j]
        ssd[temp][temp2] = ssd[temp].get(temp2,0) + 1
e = [i+1 for i in range(c)]
cpm = it.permutations(e, 3)
ming=999999999
for f in cpm:
    fl=list(f)
    cg = 0
    for i in range(3):
        for p in ssd[i].keys():cg += dtab[p][fl[i]] * ssd[i][p]
    ming = min(ming,cg)
print(ming)

Solution (Python):
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)]
    ans = [None]*3
    for k in range(3):
        costs = []
        for nc in range(c):
            cost = 0
            for i in range(n):
                s = (i+k)%3
                ci = C[i]
                for j in range(2-s, n, 3):
                    color = ci[j]-1
                    cost += D[color][nc]
            costs.append(cost)
        ans[k] = list(sorted({index:cost for index, cost in enumerate(costs)}.items(), key=lambda x: x[1]))[:3]
    out = 10**12
    for i in range(3):
        for j in range(3):
            for k in range(3):
                if len(set([ans[0][i][0], ans[1][j][0], ans[2][k][0]])) == 3:
                    out = min(out, ans[0][i][1]+ans[1][j][1]+ans[2][k][1])
    print(out)
            
    
if __name__ == "__main__":
    main()

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

G = [list(map(int,input().split())) for _ in range(N)]
g1 = []
g2 = []
g3 = []
for i in range(N):
    for j in range(N):
        G[i][j] -= 1
        if (i+j)%3 == 0:
            g1.append(G[i][j])
        if (i+j)%3 == 1:
            g2.append(G[i][j])
        if (i+j)%3 == 2:
            g3.append(G[i][j])



cost = [[0]*3 for _ in range(C)]
for c in range(C):
    for g in range(3):
        if g == 0:
            cost[c][0] = sum(D[clr_g1][c] for clr_g1 in g1)
        if g == 1:
            cost[c][1] = sum(D[clr_g2][c] for clr_g2 in g2)
        if g == 2:
            cost[c][2] = sum(D[clr_g3][c] for clr_g3 in g3)



ans = float('inf')
for c1 in range(C):
    for c2 in range(C):
        for c3 in range(C):
            temp = 0
            if c1 == c2 or c2 == c3 or c3 == c1:
                continue
            
            
            
            temp = cost[c1][0] + cost[c2][1] + cost[c3][2]
            ans = min(ans,temp)
print(ans)

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 as dd
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)]
table=[dd(int) for i in range(3)]

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

ans=10**10
for i in range(C):
    t1=0
    for x in table[0]:
        t1+=d[x][i]*table[0][x]
    for j in range(C):
        if i==j:continue
        t2=0
        for x in table[1]:
            t2+=d[x][j]*table[1][x]
        for k in range(C):
            if i==k or j==k:continue
            t3=0
            for x in table[2]:
                t3+=d[x][k]*table[2][x]
            
            ans=min(ans,t1+t2+t3)
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)]

X1=[0]*(c+1)
X2=[0]*(c+1)
X0=[0]*(c+1)

for i in range(n):
    for j in range(n):
        if (i+1+j+1)%3==0:
            X0[C[i][j]]+=1
        elif (i+1+j+1)%3==1:
            X1[C[i][j]]+=1
        else:
            X2[C[i][j]]+=1
A=[]
for c1 in range(c):
    for c2 in range(c):
        if c2==c1:
            continue
        for c3 in range(c):
            if c3==c2 or c3==c1:
                continue
            ans=0
            for i in range(1,c+1):
                ans+=X0[i]*D[i-1][c1]+X1[i]*D[i-1][c2]+X2[i]*D[i-1][c3]
            A.append(ans)
print(min(A))

Solution (Python):

import itertools

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

indices = [2, 0, 1]
count_color = [[0] * C for i in range(3)]
for i in range(N):
  idx = indices[i%3]
  for j in range(N):
    count_color[idx][c[i][j]-1] += 1
    idx = (idx + 1) % 3


ans = float('inf')
correspondence = list(itertools.permutations(range(C), 3))

for corr in correspondence:
  cost = 0
  for idx in range(3): 
    for color in range(C):
      cost += count_color[idx][color] * D[color][corr[idx]]
  ans = min(ans, cost)

print(ans)