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



Sample input:
2 3
0 1 1
1 0 1
1 4 0
1 2
3 3


Sample output:
3

Submission status: Time Limit Exceeded

Solution code:

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

G1 = []
G2 = []
G3 = []
a = int(0)

for i in range(N):
    for j in range(N):
        if (i + j) % 3 ==2:
            G1.append(c[i][j])
        elif (i + j) % 3 == 0:
            G2.append(c[i][j])
        else:
            G3.append(c[i][j])
ans_candi = []

for i1 in range(C):
    for i2 in range(C):
        for i3 in range(C):
            t = int(0)
            if i1!=i2 and i2!=i3 and i3!=i1:
                for j in G1:
                    t += D[j-1][i1]
                for j in G2:
                    t += D[j-1][i2]
                for j in G3:
                    t += D[j-1][i3]
                ans_candi.append(t)


print(min(ans_candi))

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

ans = float('inf')
for x, y, z in itertools.permutations(range(C), 3):
    point = 0
    for i, j in itertools.product(range(N), repeat=2):
        if (i + j) % 3 == 0: point += D[c[i][j] - 1][x]
        if (i + j) % 3 == 1: point += D[c[i][j] - 1][y]
        if (i + j) % 3 == 2: point += D[c[i][j] - 1][z]
    ans = min(ans, point)

print(ans)

Submission status: Time Limit Exceeded

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

cost = [[0] * C for _ in range(3)]
for p in range(C):
    for i in range(N):
        for j in range(N):
            #グループごとにかかるコストの計算
            cost[(i+j)%3][p] += D[c[i][j]][p]

res = 10 ** 9
p = [0] * 3
for p[0] in range(C):
    for p[1] in range(C):
        if p[0] == p[1]:
            continue
        for p[2] in range(C):
            if p[2] == p[0] or p[1] == p[2]:
                continue
            tmp = 0
            for i in range(3):
                tmp += cost[i][p[i]]
            res = min(res, tmp)

print(res)

Submission status: Time Limit Exceeded

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

from itertools import permutations

colors = tuple(i for i in range(C))

table = [[0 for i in range(C)] for j in range(3)]
for color in colors:
    for col in range(N):
        for row in range(N):
            table[(col+row)%3][color]+=D[c[col][row]-1][color]
            
ans = 10**9    
for i, j, k in permutations(colors, 3):
    ans = min(ans, table[0][i]+table[1][j]+table[2][k])

print(ans)

Submission status: Time Limit Exceeded

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

from itertools import permutations

colors = tuple(i for i in range(C))
lst = tuple(permutations(colors, 3))

table = [[0 for i in range(C)] for j in range(3)]
for color in colors:
    for col in range(N):
        for row in range(N):
            table[(col+row)%3][color]+=D[c[col][row]-1][color]
            
ans = 10**9    
for i, j, k in lst:
    ans = min(ans, table[0][i]+table[1][j]+table[2][k])

print(ans)

Submission status: Time Limit Exceeded

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

from itertools import permutations

colors = tuple(i+1 for i in range(C))
lst = tuple(permutations(colors, 3))

ans = 10**9
for i, j, k in lst:
    cost = 0
    for col in range(0, N, 3):
        for row in range(0, N, 3):
            cost+=D[c[col][row]-1][i-1]
        for row in range(1, N, 3):
            cost+=D[c[col][row]-1][j-1]
        for row in range(2, N, 3):
            cost+=D[c[col][row]-1][k-1]
            
    for col in range(1, N, 3):
        for row in range(0, N, 3):
            cost+=D[c[col][row]-1][j-1]
        for row in range(1, N, 3):
            cost+=D[c[col][row]-1][k-1]
        for row in range(2, N, 3):
            cost+=D[c[col][row]-1][i-1]
            
    for col in range(2, N, 3):
        for row in range(0, N, 3):
            cost+=D[c[col][row]-1][k-1]
        for row in range(1, N, 3):
            cost+=D[c[col][row]-1][i-1]
        for row in range(2, N, 3):
            cost+=D[c[col][row]-1][j-1]
            
    ans = min(cost, ans)
    
print(ans)

Submission status: Time Limit Exceeded

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

ans = float("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
            calc = 0
            for y in range(N) :
                for x in range(N) :
                    if (y+x)%3 == 0 :
                        calc += D[C[y][x]-1][i]
                    elif (y+x)%3 == 1 :
                        calc += D[C[y][x]-1][j]
                    else :
                        calc += D[C[y][x]-1][k]
            ans = min(ans,calc)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
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)]

strange = np.array([[0]*C for _ in range(3)])
for i in range(N):
    for j in range(N):
        strange[(i+j)%3] += D[c[i][j]-1]

ans = 1000*N**2
for c1 in range(C):
    for c2 in range(C):
        for c3 in range(C):
            if c1 != c2 and c2 != c3 and c3 != c1:
                ans = min(ans,strange[0][c1]+strange[1][c2]+strange[2][c3])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
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)]

strange = [defaultdict(lambda:0) for _ in range(3)]
for i in range(N):
    for j in range(N):
        for color in range(C):
            strange[(i+j)%3][color] += D[c[i][j]-1][color]

ans = 1000*N**2
ref = 0
for c1 in range(C):
    for c2 in range(C):
        for c3 in range(C):
            if c1 != c2 and c2 != c3 and c3 != c1:
                ans = min(ans,strange[0][c1]+strange[1][c2]+strange[2][c3])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#16-18をどうにかしたい
import sys 
input = sys.stdin.readline

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

mod = [[],[],[]]
for i in range(n):
    for j in range(n):
        mod[(i+j+2)%3].append([c[i][j]]+d[c[i][j]-1])

ans = 10**10
for i in range(C):
    a = 0
    for mod0 in mod[0]:
        a += mod0[i+1]
    b = a
    for j in range(C):
        a = b
        if j != i:
            for mod1 in mod[1]:
                a += mod1[j+1]
            c = a
            for k in range(C):
                a = c
                if k != i and k != j:
                    for mod2 in mod[2]:
                        a += mod2[k+1]
                    ans = min(ans,a)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys 
input = sys.stdin.readline

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

mod = [[],[],[]]
for i in range(n):
    for j in range(n):
        if (i+j+2)%3==0:
            mod[0].append([c[i][j]]+d[c[i][j]-1])
        elif (i+j+2)%3==1:
            mod[1].append([c[i][j]]+d[c[i][j]-1])
        else:
            mod[2].append([c[i][j]]+d[c[i][j]-1])

ans = 10**10
for i in range(C):
    a = 0
    for mod0 in mod[0]:
        a += mod0[i+1]
    b = a
    for j in range(C):
        a = b
        if j != i:
            for mod1 in mod[1]:
                a += mod1[j+1]
            c = a
            for k in range(C):
                a = c
                if k != i and k != j:
                    for mod2 in mod[2]:
                        a += mod2[k+1]
                    ans = min(ans,a)
print(ans)

Submission status: Time Limit Exceeded

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

ans_min = float('inf')
for i in range(C):
    j_list = list(range(C))
    j_list.remove(i)
    for j in j_list:
        k_list = list(range(C))
        k_list.remove(i)
        k_list.remove(j)
        for k in k_list:
            ans = 0
            for h in range(N):
                for w in range(N):
                    new_color = [i,j,k][(h+w) % 3]
                    ans += D[grid[h][w] - 1][new_color]
            if ans < ans_min:
                ans_min = ans
print(ans_min)

Submission status: Time Limit Exceeded

Solution code:
N, C = [int(s) for s in input().split()]

D = [0]
for i in range(C):
	D.append(list(map(lambda x: int(x), input().split())))
	D[i + 1].insert(0,0)

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

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

for i in range(1, C + 1):
	for j in range(N):
		for k in range(N):
			if (j + k) % 3 == 0:
				sumD[0][i] += D[c[j][k]][i]
			elif (j + k) % 3 == 1:
				sumD[1][i] += D[c[j][k]][i]
			else:
				sumD[2][i] += D[c[j][k]][i]

ans = float('inf')

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:
				s = sumD[0][i] + sumD[1][j] + sumD[2][k]
				if s < ans:
					ans = s

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def sol():
    n,c=map(int,input().split())
    d=[[int(i) for i in input().split()] for i in range(c)]
    t=[[int(i) for i in input().split()] for i in range(n)]
    ans=-1
    for a in range(c**2):
        for k in range(c):
            i,j=a//c,a%c
            q=[i,j,k]
            if len(set(q))<3: continue
            chk=0
            for p in range(n**2):
                h,w=p//n,p%n
                x=(h+w+2)%3
                chk+=d[t[h][w]-1][q[x]]
            if ans==-1: ans=chk
            ans=min(ans,chk)

    print(ans)

if __name__=="__main__":
    sol()

Submission status: Time Limit Exceeded

Solution code:
def sol():
    n,c=map(int,input().split())
    d=[[int(i) for i in input().split()] for i in range(c)]
    t=[[int(i) for i in input().split()] for i in range(n)]
    ans=-1
    for i in range(c):
        for j in range(c):
            for k in range(c):
                q=[i,j,k]
                if len(set(q))<3: continue
                chk=0
                for p in range(n**2):
                    h,w=p//n,p%n
                    x=(h+w+2)%3
                    chk+=d[t[h][w]-1][q[x]]
                if ans==-1: ans=chk
                ans=min(ans,chk)

    print(ans)

if __name__=="__main__":
    sol()

Submission status: Time Limit Exceeded

Solution code:
# ContestName
# URL
import sys
import numpy as np

s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in ss]
ss2nnn = lambda ss: [s2nn(s) for s in ss]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [sys.stdin.readline().rstrip() for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

def main():
    N, C = i2nn()
    D = np.array(ii2nnn(C))
    c = np.array(ii2nnn(N))
    E = np.array([[0] * C for _ in range(3)])
    for i in range(N):
        for j in range(N):
            before = c[i,j]
            e = (i+j) % 3
            E[e,:] += D[before-1,:]
    iwakan = N * N * 1000
    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
                n = E[0,c1] + E[1,c2] + E[2,c3]
                if n < iwakan:
                    iwakan = n
    print(iwakan)

main()

Submission status: Time Limit Exceeded

Solution code:
# ContestName
# URL
import sys
import numpy as np

s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in ss]
ss2nnn = lambda ss: [s2nn(s) for s in ss]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [sys.stdin.readline().rstrip() for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

def main():
    N, C = i2nn()
    D = np.array(ii2nnn(C))
    c = np.array(ii2nnn(N))
    E = np.array([[0] * C for _ in range(3)])
    for i in range(N):
        for j in range(N):
            before = c[i][j]
            e = (i+j) % 3
            for after in range(1, C+1):
                E[e][after-1] += D[before-1][after-1]
    iwakan = N * N * 1000
    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
                n = E[0][c1] + E[1][c2] + E[2][c3]
                if n < iwakan:
                    iwakan = n
    print(iwakan)

main()

Submission status: Time Limit Exceeded

Solution code:
# ContestName
# URL
import sys
#import numpy as np

s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in ss]
ss2nnn = lambda ss: [s2nn(s) for s in ss]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [sys.stdin.readline().rstrip() for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

def main():
    N, C = i2nn()
    D = ii2nnn(C)
    c = ii2nnn(N)
    def main2(afters):
        #print('step %d' % cl)
        n = 0
        for i in range(N):
            for j in range(N):
                before = c[i][j]
                after = afters[(i + j) % 3]
                if before  == after:
                    continue
                iwakan = D[before-1][after-1]
                n += iwakan
        return n
    iwakan = N * N * 1000
    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
                n = main2((c1+1, c2+1, c3+1))
                if n < iwakan:
                    iwakan = n
    print(iwakan)

main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys

def calc(order, groups, D):
    ret = 0
    for i, G in enumerate(groups):
        target = order[i]
        for elm in G:
            #print(elm, target)
            ret += D[elm - 1][target]
    return ret

def dfs(idx, current, used, groups, D):
    if idx == 3:
        ret = calc(current, groups, D)
        return ret
    ret = float('inf')
    for i, u in enumerate(used):
        if not u:
            used[i] = True
            tmp = dfs(idx + 1, current + [i], used, groups, D)
            ret = min(ret, tmp)
            used[i] = False
    return ret

def solve(N: int, C: int, D: "List[List[int]]", c: "List[List[int]]"):
    groups = [[] for _ in range(3)]
    for i in range(N):
        for j in range(N):
            cc = c[i][j]
            groups[(i + j) % 3].append(cc)
    #print(groups)
    ret = dfs(0, [], [False] * C, groups, D)
    print(ret)
    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))  # type: int
    C = int(next(tokens))  # type: int
    D = [ [ int(next(tokens)) for _ in range(C) ] for _ in range(C) ]  # type: "List[List[int]]"
    c = [ [ int(next(tokens)) for _ in range(N) ] for _ in range(N) ]  # type: "List[List[int]]"
    solve(N, C, D, c)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from itertools import*
from math import*
from collections import*
from heapq import*
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf = 10**18
mod = 10**9+7
from functools import reduce
import sys
sys.setrecursionlimit(10**7)

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 = inf
for (a,b,c) in permutations(range(c),3):
    cur = 0
    for i in range(n):
        for j in range(n):
            if (i+j)%3 == 0:
                cur += D[C[i][j]-1][a]
            elif (i+j)%3 == 1:
                cur += D[C[i][j]-1][b]
            else:
                cur += D[C[i][j]-1][c]
    ans = min(ans,cur)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import*
import sys
input=sys.stdin.readline
n,c=map(int,input().split())
cost=[list(map(int,input().split()))for i in range(c)]
d=[[],[],[]]
for i in range(n):
    for j,v in enumerate(map(int,input().split())):
        d[(i+j+2)%3].append(v-1)
ans=[]
for cmb in permutations(range(c),3):
    ans.append(sum(sum(cost[i][cmb[dindex]]for i in d[dindex])for dindex in range(3)))
print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
from collections import*
from itertools import*
import sys
input=sys.stdin.readline
n,c=map(int,input().split())
cost=[list(map(int,input().split()))for i in range(c)]
d=defaultdict(list)
for i in range(n):
    for j,v in enumerate(map(int,input().split())):
        d[(i+j+2)%3].append(v-1)
ans=[]
for cmb in permutations(range(c),3):
    ans.append(sum(sum(cost[i][cmb[dindex]]for i in d[dindex])for dindex in range(3)))
print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
from collections import*
from itertools import*
n,c=map(int,input().split())
cost=[list(map(int,input().split()))for i in range(c)]
grid=[list(map(int,input().split()))for i in range(n)]
d=defaultdict(list)
for i in range(1,n+1):
    for j in range(1,n+1):
        d[(i+j)%3].append(grid[i-1][j-1]-1)
ans=[]
for cmb in permutations(range(c),3):
    ans.append(sum(sum(cost[i][cmb[dindex]]for i in d[dindex])for dindex in range(3)))
print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
import copy
N , C = map(int, input().split())
ds =[list(map(int, input().split())) for i in range(C)]
cs =[list(map(int, input().split())) for i in range(N)]
c0 = []
c1 = []
c2 = []
for i in range(N):
    for j in range(N):
        if (i+j) % 3 == 0:
            c0.append(cs[i][j])
        elif (i+j) % 3 == 1:
            c1.append(cs[i][j])
        else:
            c2.append(cs[i][j])
d = 10**9
l0 = len(c0)
l1 = len(c1)
l2 = len(c2)
for i in range(C):
    d0 = 0
    for l in range(l0):
         if (c0[l]-1) != i:
            d0 += ds[c0[l]-1][i]
    for j in range(C):
        if i == j:
            continue
        d1 = copy.copy(d0)
        for h in range(l1):
            if (c1[h]-1) != j:
                d1 += ds[c1[h]-1][j]
        for k in range(C):
            if i == k or j == k:
                continue
            d2 = copy.copy(d1)
            for l in range(l2):
                if (c2[l]-1) != k:
                    d2 += ds[c2[l]-1][k]
            if d > d2:
                d = d2
print(d)

Submission status: Time Limit Exceeded

Solution code:
import copy
N , C = map(int, input().split())
ds =[list(map(int, input().split())) for i in range(C)]
cs =[list(map(int, input().split())) for i in range(N)]
c0 = []
c1 = []
c2 = []
for i in range(N):
    for j in range(N):
        if (i+j) % 3 == 0:
            c0.append(cs[i][j])
        elif (i+j) % 3 == 1:
            c1.append(cs[i][j])
        else:
            c2.append(cs[i][j])
d = 10**9
l0 = len(c0)
l1 = len(c1)
l2 = len(c2)
for i in range(C):
    d0 = 0
    for l in range(l0):
         if (c0[l]-1) != i:
            d0 += ds[c0[l]-1][i]
    for j in range(C):
        if i == j:
            continue
        d1 = copy.copy(d0)
        for h in range(l1):
            if (c1[h]-1) != j:
                d1 += ds[c1[h]-1][j]
        for k in range(C):
            if i == k or j == k:
                continue
            d2 = copy.copy(d1)
            for l in range(l2):
                if (c2[l]-1) != k:
                    d2 += ds[c2[l]-1][k]
            if d > d2:
                d = d2
print(d)

Submission status: Time Limit Exceeded

Solution code:
N , C = map(int, input().split())
ds =[list(map(int, input().split())) for i in range(C)]
cs =[list(map(int, input().split())) for i in range(N)]
c0 = []
c1 = []
c2 = []
for i in range(N):
    for j in range(N):
        if (i+j) % 3 == 0:
            c0.append(cs[i][j])
        elif (i+j) % 3 == 1:
            c1.append(cs[i][j])
        else:
            c2.append(cs[i][j])
d = 10**9
l0 = len(c0)
l1 = len(c1)
l2 = len(c2)
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
            d0 = 0
            for l in range(l0):
                if (c0[l]-1) != i:
                    d0 += ds[c0[l]-1][i]
            for h in range(l1):
                if (c1[h]-1) != j:
                    d0 += ds[c1[h]-1][j]
            for l in range(l2):
                if (c2[l]-1) != k:
                    d0 += ds[c2[l]-1][k]
            if d > d0:
                d = d0
print(d)

Submission status: Time Limit Exceeded

Solution code:
import sys
import re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits


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


sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

n, c = MAP()

d_lis = [LIST() for _ in range(c)]
c_lis = [LIST() for _ in range(n)]

jouyo = [[], [], []]


sum_0 = [0]*c
sum_1 = [0]*c
sum_2 = [0]*c

for i in range(n):
    for j in range(n):
        if ((i + j + 2) % 3 == 0):
            for k in range(1, c+1):
                if(k != c_lis[i][j]):
                    sum_0[k-1] += d_lis[c_lis[i][j]-1][k-1]
        elif ((i + j + 2) % 3 == 1):
            for k in range(1, c+1):
                if(k != c_lis[i][j]):
                    sum_1[k-1] += d_lis[c_lis[i][j]-1][k-1]
        else:
            for k in range(1, c+1):
                if(k != c_lis[i][j]):
                    sum_2[k-1] += d_lis[c_lis[i][j]-1][k-1]


kouho = [sum_0, sum_1, sum_2]

ans = INF

for i in range(c):
    for j in range(c):
        for k in range(c):
            if (i != j and j != k and i != k):
                #print(sum_0[i], sum_1[j], sum_2[k])
                ans = min(sum_0[i] + sum_1[j] + sum_2[k], ans)


print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits

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()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

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

group0 = []
group1 = []
group2 = []
for i in range(N):
	for j in range(N):
		if (i+j)%3 == 0:
			group0.append(c[i][j]-1)
		elif (i+j)%3 == 1:
			group1.append(c[i][j]-1)
		elif (i+j)%3 == 2:
			group2.append(c[i][j]-1)
# print(group0)
# print(group1)
# print(group2)

color_0 = []
for i in range(C):
	tmp = 0
	for item0 in group0:
		tmp += D[item0][i]
	color_0.append((tmp, i))
color_0 = sorted(color_0)[0:3]
color_0_lis = [x[1] for x in color_0]

color_1 = []
for i in range(C):
	tmp = 0
	for item1 in group1:
		tmp += D[item1][i]
	color_1.append((tmp, i))
color_1 = sorted(color_1)[0:3]
color_1_lis = [x[1] for x in color_1]

color_2 = []
for i in range(C):
	tmp = 0
	for item2 in group2:
		tmp += D[item2][i]
	color_2.append((tmp, i))
color_2 = sorted(color_2)[0:3]
color_2_lis = [x[1] for x in color_2]
# print(color_0)
# print(color_0_lis)
# print(color_1)
# print(color_1_lis)
# print(color_2)
# print(color_2_lis)
ans = INF
for i in color_0_lis:
	for j in color_1_lis:
		for k in color_2_lis:
			tmp = 0
			if i == j or j == k or k == i:
				continue
			else:
				for item0 in group0:
					tmp += D[item0][i]
				for item1 in group1:
					tmp += D[item1][j]
				for item2 in group2:
					tmp += D[item2][k]
				ans = min(ans, tmp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits

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()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

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

group0 = []
group1 = []
group2 = []
for i in range(N):
	for j in range(N):
		if (i+j)%3 == 0:
			group0.append(c[i][j]-1)
		elif (i+j)%3 == 1:
			group1.append(c[i][j]-1)
		elif (i+j)%3 == 2:
			group2.append(c[i][j]-1)
# print(group0)
# print(group1)
# print(group2)

color_0 = []
for i in range(C):
	tmp = 0
	for item0 in group0:
		tmp += D[item0][i]
	color_0.append((tmp, i))
color_0 = sorted(color_0)[::-1]
color_0 = [x[1] for x in color_0]

color_1 = []
for i in range(C):
	tmp = 0
	for item1 in group1:
		tmp += D[item1][i]
	color_1.append((tmp, i))
color_1 = sorted(color_1)[::-1]
color_1 = [x[1] for x in color_1]

color_2 = []
for i in range(C):
	tmp = 0
	for item2 in group2:
		tmp += D[item2][i]
	color_2.append((tmp, i))
color_2 = sorted(color_2)[::-1]
color_2 = [x[1] for x in color_2]
# print(color_0)
# print(color_1)
# print(color_2)
ans = INF
for i in color_0:
	for j in color_1:
		for k in color_2:
			tmp = 0
			if i == j or j == k or k == i:
				continue
			else:
				for item0 in group0:
					tmp += D[item0][i]
				for item1 in group1:
					tmp += D[item1][j]
				for item2 in group2:
					tmp += D[item2][k]
				ans = min(ans, tmp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits

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()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

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

group0 = []
group1 = []
group2 = []
for i in range(N):
	for j in range(N):
		if (i+j)%3 == 0:
			group0.append(c[i][j]-1)
		elif (i+j)%3 == 1:
			group1.append(c[i][j]-1)
		elif (i+j)%3 == 2:
			group2.append(c[i][j]-1)
# print(group0)
# print(group1)
# print(group2)

ans = INF
for i in range(C):
	for j in range(C):
		for k in range(C):
			tmp = 0
			if i == j or j == k or k == i:
				continue
			else:
				for item0 in group0:
					tmp += D[item0][i]
				for item1 in group1:
					tmp += D[item1][j]
				for item2 in group2:
					tmp += D[item2][k]
				ans = min(ans, tmp)
print(ans)

Submission status: Time Limit Exceeded

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

ans = 10000*N*N
for i in range(C):
    cur_score = 0
    for x in range(N):
        for y in range((-x)%3,N,3):
            cur_score += D[c[x][y]][i]
    if cur_score>ans:
        continue
    for j in range(C):
        cur_score2 = 0
        if j == i:
            continue
        for x in range(N):
            for y in range((1-x)%3,N,3):
                cur_score2 += D[c[x][y]][j]
        if cur_score+cur_score2>ans:
            continue
        
        for k in range(C):
            cur_score3 = 0
            if k == j or k == i:
                continue
            for x in range(N):
                for y in range((2-x)%3,N,3):
                    cur_score3 += D[c[x][y]][k]
            ans = min(ans,cur_score+cur_score2+cur_score3)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools

N, C = map(int, input().split())
D = [ [ int(x) for x in input().split() ] for _ in range(C) ]
CC = [ [ int(x)-1 for x in input().split() ] for _ in range(N) ]
cost = [ [ 0 for _ in range(C) ] for _ in range(3) ]

for c in range(C):
    for i in range(N):
        for j in range(N):
            cost[(i+j) % 3][c] += D[CC[i][j]][c]

ans = float("inf")
for c in itertools.permutations(range(C), 3):
    tmp = 0
    for j in range(3):
        tmp += cost[j][c[j]]

    ans = min(ans, tmp)

print(ans)