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 sys
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  

N,C = LI()
D = [[0]*(C+1)] + [[0]+LI() for _ in range(C)]
c = [[0]*(N+1)] + [[0]+LI() for _ in range(N)]

from collections import defaultdict

d0,d1,d2 = defaultdict(int),defaultdict(int),defaultdict(int)

for i in range(1,N+1):
    for j in range(1,N+1):
        if (i + j) % 3 == 0:
            d0[c[i][j]] += 1
        elif (i + j) % 3 == 1:
            d1[c[i][j]] += 1
        elif (i + j) % 3 == 2:
            d2[c[i][j]] += 1

ans = 10**18

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 k == i:
                continue
            else:
                a = 0
                for color in d0.keys():
                    a += D[color][i]*d0[color]
                for color in d1.keys():
                    a += D[color][j]*d1[color]
                for color in d2.keys():
                    a += D[color][k]*d2[color]
                ans = min(ans,a)

print(ans)

Solution (Python):
from itertools import permutations
INF=10**18
n,c=map(int,input().split())
d=[list(map(int,input().split())) for _ in range(c)]
a=[list(map(int,input().split())) for _ in range(n)]
dp=[[0 for _ in range(c)]for i in range(3)]
for i in range(n):
  for j in range(n):
    dp[(i+j)%3][a[i][j]-1]+=1
li=list(permutations(list(range(c)),3))
fans=INF
for i,j,k in li:
  ans=0
  for x in range(c):
    ans+=dp[0][x]*d[x][i]
    ans+=dp[1][x]*d[x][j]
    ans+=dp[2][x]*d[x][k]
  fans=min(fans,ans)
print(fans)

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

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

iwa = [[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(grids[i])):
            iwa[i][j]+=D[grids[i][k]][j]

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

print(ans)

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

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

iwa = [[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(grids[i])):
            iwa[i][j]+=D[grids[i][k]][j]

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

print(ans)

Solution (Python):
from itertools import permutations
n,C=map(int,input().split())
d=[list(map(int,input().split())) for _ in range(C)]
c=[list(map(int,input().split())) for _ in range(n)]
a=[[0]*C for _ in range(3)]
for i in range(n):
	for j in range(n):
		a[(i+j)%3][c[i][j]-1]+=1
ans=10**9
for v in permutations(range(C),3):
	tmp=0
	for i in range(3):
		for j in range(C):
			tmp+=a[i][j]*d[j][v[i]]
	ans=min(ans,tmp)
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)]

num = []
for i in range(C):
    for j in range(C):
        if i == j:
            continue
        else:
            for k in range(C):
                if i == k or j == k:
                    continue
                else:
                    num.append((i,j,k))
                    
col = [[0]*C for _ in range(3)]

for i in range(n):
    for j in range(n):
        x = c[i][j]-1
        y = (i+j) % 3
        
        col[y][x] += 1
    
ans = 1145141919810
for ll in num:
    a = 0
    for i in range(3):
        for j in range(C):
            a += col[i][j] * d[j][ll[i]]
            
    ans = min(ans,a)
    
print(ans)

Solution (Python):


from collections import defaultdict
import itertools

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


dict_c = [defaultdict(int) for _ in range(3)]
for i in range(N):
    c = list(int(x) for x in input().split())
    for j in range(N):
        dict_c[(i+j)%3][c[j]-1] += 1



list_C = list(range(C))
ans = 10**18
for (p, q, r) in itertools.permutations(list_C, 3):
    tmp = 0
    for i, j in enumerate((p, q, r)):
        for m, n in dict_c[i].items():
            tmp += D[m][j] * n
    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)]
A=[list(map(int,input().split())) for i in range(N)]
X=[[0]*C for i in range(3)]
for c in range(C):
  for i in range(N):
    for j in range(N):
      X[(i+j)%3][c]+=D[A[i][j]-1][c]
P=10**20
for i in range(C):
  for j in range(C):
    for k in range(C):
      if len(set([i,j,k]))==3:
        P=min(P,X[0][i]+X[1][j]+X[2][k])
print(P)

Solution (Python):
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i for _ in range(j)]





N, C = mi()
D = li2(C)
S = li2(N)

table = dp2(0, C, 3)
'''

    
        for color in range(C):
            i = 0
            j = start
            print(i, j)
            while True:
                table[num][color] += D[S[i][j]-1][color]
                if j < 1 or i >= N:
                    break
                j -= 1
                i += 1
'''
for i in range(N):
    for j in range(N):
        for color in range(C):
            table[(i+j)%3][color] += D[S[i][j]-1][color]

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

print(ans)

Solution (Python):
import sys
from collections import defaultdict
import itertools

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: map(int, read().split())
in_s = lambda: readline().rstrip().decode('utf-8')


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

    grid = [defaultdict(int) for _ in range(3)]

    for y in range(N):
        for x in range(N):
            d = grid[(x + y + 2) % 3]
            d[c[y][x]] += 1

    comb = itertools.permutations(range(1, C + 1), 3)

    ans = 10**9 + 7
    for com in comb:
        iwa = 0
        for i in range(3):
            n_c = com[i]
            for k, v in grid[i].items():
                iwa += D[k - 1][n_c - 1] * v
        ans = min(ans, iwa)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import defaultdict
import itertools

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: map(int, read().split())
in_s = lambda: readline().rstrip().decode('utf-8')


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

    grid = [defaultdict(int) for _ in range(3)]

    for y in range(N):
        for x in range(N):
            d = grid[(x + y + 2) % 3]
            d[c[y][x]] += 1

    comb = itertools.permutations(range(1, C + 1), 3)

    ans = 10**9 + 7
    for com in comb:
        iwa = 0
        for i in range(3):
            n_c = com[i]
            for k, v in grid[i].items():
                iwa += D[k - 1][n_c - 1] * v
        ans = min(ans, iwa)

    print(ans)


if __name__ == '__main__':
    main()

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

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

for i in range(N):
  for j in range(N):
    tmp=(i+j)%3
    
    for d in range(C):
      grid[tmp][d]+=D[c[i][j]-1][d]
      
print(min([grid[0][x]+grid[1][y]+grid[2][z] for x in range(C) for y in range(C) for z in range(C) if x!=y and y!=z and z!=x]))

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7






N, C = getNM()
D = [getList() for i in range(C)]
maze = [getList() for i in range(N)]

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

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

ans = float('inf')
for vi in permutations([i for i in range(C)], 3):
    opt_0, opt_1, opt_2 = vi
    cnt = 0
    for i in range(C):
        cnt += lis[0][i] * D[i][opt_0]
        cnt += lis[1][i] * D[i][opt_1]
        cnt += lis[2][i] * D[i][opt_2]
    ans = min(ans, cnt)
print(ans)

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





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






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count




N,C = IL()
D = ILL(C)

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

for i in range(N):
  temp = IL()
  for j in range(N):
    data[(i+j)%3][temp[j]-1] += 1

MIN = INF
for a in range(C):
  for b in range(C):
    for c in range(C):
      if (a-b)*(b-c)*(c-a):
        score = 0
        for j in range(C):
          score += D[j][a]*data[0][j]
          score += D[j][b]*data[1][j]
          score += D[j][c]*data[2][j]
        MIN = min(MIN,score)
print(MIN)

Solution (Python):


import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
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,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n,c=MI()
colors=[LI() for i in range(c)]
grid=[LI() for i in range(n)]
lis0=[]
lis1=[]
lis2=[]
for i in range(n):
    for j in range(n):
        if (i+j)%3==0:
            lis0.append(grid[i][j]-1)
        elif (i+j)%3==1:
            lis1.append(grid[i][j]-1)
        else:
            lis2.append(grid[i][j]-1)

c0=Counter(lis0)
c1=Counter(lis1)
c2=Counter(lis2)
ind=[i for i in range(c)]
mn=inf
for i in product(ind,repeat=3):
    ans=0
    if i[0]==i[1] or i[1]==i[2] or i[2]==i[0]:
        continue
    
    for x in c0.keys():
        
        ans+=c0[x]*colors[x][i[0]]
    for y in c1.keys():
        
        ans+=c1[y]*colors[y][i[1]]
    for z in c2.keys():
        
        ans+=c2[z]*colors[z][i[2]]
    if ans<mn:
        mn=ans
print(mn)

Solution (Python):
n , c = map(int,input().split())
iwaka = [list(map(int,input().split())) for i in range(c)]
masu = [list(map(int,input().split())) for i in range(n)]
amari = [{} for i in range(3)]

for i in range(n):
    for j in range(n):
        amari[(i+j)%3][masu[i][j]] = amari[(i+j)%3].get(masu[i][j],0) + 1

kouho = []
for i in range(c):
    for j in range(c):
        for k in range(c):
            if i != j and j != k and k != i:
                kouho.append((i+1,j+1,k+1))
ans = 10**9
for p in kouho:
    cou = 0
    for i in range(3):
        for k , v in amari[i].items():
            cou += iwaka[k-1][p[i]-1]*v
    ans = min(ans,cou)
print(ans)

Solution (Python):
import sys
from collections import defaultdict
from heapq import heappush, heappop
def input(): return sys.stdin.readline().strip()


def main():
    N, C = map(int, input().split())
    D = [list(map(int, input().split())) for _ in range(C)]
    mod = [defaultdict(int), defaultdict(int), defaultdict(int)]
    for i in range(N):
        c = list(map(int, input().split()))
        for j in range(N):
            mod[(i + j) % 3][c[j] - 1] += 1
    
    
    hq = [[], [], []]
    for i in range(3):
        for y in range(C):
            diff = 0
            for x in mod[i]: diff += D[x][y] * mod[i][x]
            heappush(hq[i], (diff, y))
    
    
    cand = [[], [], []]
    for i in range(3):
        for _ in range(3):
            diff, color = heappop(hq[i])
            cand[i].append((diff, color))
    
    ans = 10**18
    for p in cand[0]:
        for q in cand[1]:
            for r in cand[2]:
                if p[1] == q[1] or q[1] == r[1] or r[1] == p[1]: continue
                ans = min(ans, p[0] + q[0] + r[0])
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
n,nc=map(int,input().split())
d=[list(map(int,input().split())) for _ in range(nc)]
c=[list(map(int,input().split())) for _ in range(n)]
from collections import defaultdict
dct=defaultdict(int)
for x in range(n):
  for y in range(n):
    for ci in range(nc):
      if (ci,(x+y)%3) in dct:
        dct[(ci,(x+y)%3)]+=d[c[x][y]-1][ci]
      else:
        dct[(ci,(x+y)%3)]=d[c[x][y]-1][ci]

def func(c1,c2,c3): 
  ret=dct[(c1,0)]+dct[(c2,1)]+dct[(c3,2)]
  return ret
ans=float('inf')
for c1 in range(nc):
  for c2 in range(nc):
    if c1==c2:continue
    for c3 in range(nc):
      if c1==c3 or c2==c3:continue
      ans=min(ans,func(c1,c2,c3))
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 i in range(C)]
c = [list(map(lambda s: int(s) - 1, input().split())) for i in range(N)]

d = [Counter(sum([c[j][(i - j) % 3::3] for j in range(N)], []))
     for i in range(3)]
ans = 1000000007
for t in permutations(range(C), 3):
    dis = 0
    for i in range(3):
        for k, v in d[i].items():
            dis += D[k][t[i]] * v
    ans = min(dis, ans)
print(ans)

Solution (Python):





import math
import fractions
import sys
import bisect
import heapq  
import collections
from collections import Counter
from collections import deque
import pprint

sr = lambda: input()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

"""nを素因数分解"""
"""2以上の整数n => [[素因数, 指数], ...]の2次元リスト"""


def factorization(n):
    arr = []
    temp = n
    if n == 1:
        return arr

    for i in range(2, int(-(-n ** 0.5 // 1)) + 1):
        if temp % i == 0:
            cnt = 0
            while temp % i == 0:
                cnt += 1
                temp //= i
            arr.append([i, cnt])

    if temp != 1:
        arr.append([temp, 1])

    if arr == []:
        arr.append([n, 1])

    return arr



def power(a, n, mod):
    x = 1
    while n:
        if n & 1:
            x *= a % mod
        n >>= 1
        a *= a % mod
    return x % mod



def kaijo(n, l, mod):
    if n == 0:
        return 1
    a = n
    tmp = n - 1
    while (tmp >= l):
        a = a * tmp % mod
        tmp -= 1
    return a


inf = 10 ** 18
mod = 10 ** 9 + 7

n,k = lr()
d = [lr() for i in range(k)]
c = [lr() for i in range(n)]
ans = [0 for i in range(3)]
pre = inf
fir = []
sec = []
thr = []
firkouho = []
seckouho = []
thrkouho = []
for y in range(n):
    for x in range(n):
        if (y + x) % 3 == 0:
            fir.append(c[y][x]-1)
        elif (y + x) % 3 == 1:
            sec.append(c[y][x]-1)
        else:
            thr.append(c[y][x] - 1)

for i in range(k):
    ans[0] = 0
    for ind in fir:
        ans[0] += d[ind][i]
    firkouho.append([ans[0], i])

for i in range(k):
    ans[1] = 0
    for ind in sec:
        ans[1] += d[ind][i]
    seckouho.append([ans[1], i])

for i in range(k):
    ans[2] = 0
    for ind in thr:
        ans[2] += d[ind][i]
    thrkouho.append([ans[2], i])

firkouho.sort()
seckouho.sort()
thrkouho.sort()

for i in range(k):
    ans[0] = 0
    ans[0],ind1 = firkouho[i]
    for j in range(k):
        if seckouho[j][1] != ind1:
            ans[1] = 0
            ans[1],ind2 = seckouho[j]
            for l in range(k):
                if thrkouho[l][1] != ind1 and thrkouho[l][1] != ind2:
                    ans[2] = 0
                    ans[2],ind3 = thrkouho[l]
                    pre = min(pre,sum(ans))
print(pre)

Solution (Python):
from itertools import permutations

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


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


cost = [[] for _ in range(3)]

for i in range(3):
    for s in range(C):
        tmp = 0
        for t in rem[i]:
            tmp += D[t-1][s]
        cost[i].append((tmp, s+1))

for i in cost:
    i.sort()
    i = i[:3]
 
ans = 1e10
for i in cost[0]:
    for j in cost[1]:
        for h in cost[2]:
            if i[1] != j[1] and j[1] != h[1] and h[1] != i[1]:
                ans = min(ans,i[0]+j[0]+h[0])
print(ans)

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):
from itertools import permutations

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

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

cost = [[] for _ in range(3)]

for i in range(3):
    for s in range(C):
        tmp = 0
        for t in rem[i]:
            tmp += D[t-1][s]
        cost[i].append((tmp,s+1))

for i in cost:
    i.sort()
    i = i[:3]

ans = 1e10
for i in cost[0]:
    for j in cost[1]:
        for h in cost[2]:
            if i[1] != j[1] and j[1] != h[1] and h[1] != i[1]:
                ans = min(ans,i[0]+j[0]+h[0])
print(ans)

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)]
Z = [0]*C
O = [0]*C
T = [0]*C
for x in range(N):
    for y in range(N):
        if (x+y)%3 == 0:
            Z[G[x][y]-1] += 1
        elif (x+y)%3 == 1:
            O[G[x][y]-1] += 1
        else:
            T[G[x][y]-1] += 1

ans = 10**9
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
            temp = 0
            for k in range(C):
                temp += Z[k]*D[k][c1]
            for k in range(C):
                temp += O[k]*D[k][c2]
            for k in range(C):
                temp += T[k]*D[k][c3]
            ans = min(ans,temp)

print(ans)

Solution (Python):
import itertools

n, c = map(int, input().split())
d = []
for i in range(c):
    di = list(map(int, input().split()))
    d.append(di)
dic0 = {}
dic1 = {}
dic2 = {}
for i in range(1, n+1):
    ci = list(map(int, input().split()))
    for j in range(n):
        cj = ci[j]
        if (i+j+1)%3 == 0:
            if cj in dic0:
                dic0[cj] += 1
            else:
                dic0[cj] = 1
        elif (i+j+1)%3 == 1:
            if cj in dic1:
                dic1[cj] += 1
            else:
                dic1[cj] = 1
        else:
            if cj in dic2:
                dic2[cj] += 1
            else:
                dic2[cj] = 1

ans = 10**9
for c0, c1, c2 in itertools.permutations(list(range(1, c+1)), 3):
    temp = 0
    for key in dic0.keys():
        if key != c0:
            temp += d[key-1][c0-1] * dic0[key]
    for key in dic1.keys():
        if key != c1:
            temp += d[key-1][c1-1] * dic1[key]
    for key in dic2.keys():
        if key != c2:
            temp += d[key-1][c2-1] * dic2[key]
    ans = min(ans, temp)
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)]

for i, l in enumerate(C):
    l = [x-1 for x in l]
    C[i] = l

import itertools
ans = 10**18

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


for p in itertools.permutations(range(c), 3):
    temp = 0
    for i in range(3):
        for j in range(c):
            temp += X[j][i]*(D[j][p[i]])
    ans = min(temp, ans)
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())))
colors = [[0]*C for _ in range(3)]
for i in range(N):
    for j in range(N):
        colors[(i+j)%3][c[i][j]-1] += 1
ans = 10**10
for i in range(C):
    for j in range(C):
        if i==j:
            continue
        for k in range(C):
            if j==k or k==i:
                continue
            tmp = 0
            for l in range(C):
                tmp += colors[0][l]*D[l][i]
                tmp += colors[1][l]*D[l][j]
                tmp += colors[2][l]*D[l][k]
            ans = min(ans, tmp)
print(ans)

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):
def resolve():
    N, Cnum = list(map(int, input().split()))
    D = [list(map(int, input().split())) for _ in range(Cnum)]
    C = [list(map(int, input().split())) for _ in range(N)]
    color_count = [{}, {}, {}]
    for i in range(N):
        for j in range(N):
            group = (i+j)%3
            d = color_count[group]
            if C[i][j]-1 in d:
                d[C[i][j]-1] += 1
            else:
                d[C[i][j]-1] = 1
    
    ans = float("inf")
    import itertools
    for pattern in itertools.permutations(list(range(0, Cnum)), 3):
        total = 0
        for i, after in enumerate(pattern):
            for color, count in color_count[i].items():
                total += count*D[color][after]
        ans = min(ans, total)
    print(ans)

if '__main__' == __name__:
    resolve()

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=10**18
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

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from collections import Counter
    n, c = map(int, readline().split())
    cost = [list(map(int, readline().split())) for _ in range(c)]
    color = [list(map(int, readline().split())) for _ in range(n)]

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

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

    from itertools import permutations

    ans = INF

    for after in permutations(range(1, c + 1), 3):
        score = 0
        for gn, counter in enumerate(group):
            for key, val in counter.items():
                score += val * cost[key - 1][after[gn] - 1]
        ans = min(score, ans)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):

from collections import defaultdict
import itertools
n, c = map(int, input().split())
D = [list(map(int, input().split()))for _ in range(c)]


diago = [defaultdict(int)for _ in range(3)]
for i in range(n):
    for j, color in enumerate(map(int, input().split())):
        diago[(i+j) % 3][color-1] += 1


costs = [[0]*c for _ in range(3)]
for i in range(3):
    for j in range(c):
        for k, v in diago[i].items():
            costs[i][j] += D[k][j]*v

INF = 10**18
ans = INF
for trio in itertools.combinations(range(c), 3):
    for color in itertools.permutations(trio, 3):
        cost = sum(costs[i][j] for i, j in enumerate(color))
        if cost < ans:
            ans = cost
print(ans)