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: Wrong Answer

Solution code:
import numpy as np
N, C = map(int, input().split(' '))
diff = [list(map(int, input().split(' '))) for _ in range(C)]
tiles = [[0 for _ in range(C)] for _ in range(3)]
r = 2
for i in range(N):
    tmp = list(map(int, input().split(' ')))
    for j, c in enumerate(tmp):
        tiles[(r+j)%3][c-1] += 1
    r = (r + 1) % 3
check_tile = np.array(tiles).T
flag = 0

for ar in check_tile:
    if len(np.where(ar > 0)[0]) > 1:
        flag = 1
        break

if flag == 1:
    iwakan = np.dot(np.array(tiles), np.array(diff))
    iwakan[np.where(iwakan == 0)] = 1000000
    
    res = float('INF')
    for i in range(C):
        for j in range(C):
            for k in range(C):
                if i != j and j != k and k != i:
                    res = min(res, iwakan[0][i] + iwakan[1][j] + iwakan[2][k])
    print(res)
else:
    print(0)

Submission status: Wrong Answer

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

group0 = []
group1 = []
group2 = []
for x in range(N):
    for y in range(N):
        if (x + y) % 3 == 0:
            group0.append(grids[y][x])
        elif (x + y) % 3 == 1:
            group1.append(grids[y][x])
        elif (x + y) % 3 == 2:
            group2.append(grids[y][x])


def calcColst(group, color):
    cost = 0
    for grid in group:
        if grid == color:
            continue
        cost += D[color - 1][grid - 1]
    return cost


minCost = 100000000
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
            allCost = calcColst(group0, i) + calcColst(group1, j) + calcColst(
                group2, k)
            minCost = min(minCost, allCost)

print(minCost)

Submission status: Wrong Answer

Solution code:
s=input().split()
N=int(s[0])
C=int(s[1])
d=[]
for i in range(C):
    s=input().split()
    temp=[]
    for item in s:
        temp.append(int(item))
    d.append(temp)
if N==1:
    print("0")
else:
    c=[[],[],[]]
    cost=[[],[],[]]
    for j in range(N):
        s=input().split()
        for i in range(len(s)):
            c[(i+j)%3].append(int(s[i])-1)
    for i in range(C):
        s=0
        for col in c[0]:
            s+=d[col][i]
        cost[0].append((s,i))
        s=0
        for col in c[1]:
            s+=d[col][i]
        cost[1].append((s,i))
        s=0
        for col in c[2]:
            s+=d[col][i]
        cost[2].append((s,i))
    cost[0].sort()
    cost[1].sort()
    cost[2].sort()
    res=3000000
    for i in range(C):
        for j in range(C):
            for k in range(C):
                if cost[0][i][1]!=cost[1][j][1] and cost[1][j][1]!=cost[2][k][1] and cost[2][k][1]!=cost[0][i][1]:
                    res=min(res,cost[0][i][0]+cost[1][j][0]+cost[2][k][0])
                if cost[0][i][0]+cost[1][j][0]+cost[2][k][0]>res:
                    break
    print(res)

Submission status: Wrong Answer

Solution code:
n,b=map(int,input().split())
d=[list(map(int,input().split()))for _ in[0]*b]
c=[list(map(int,input().split()))for _ in[0]*n]
mods=[{},{},{}]
for i in range(n):
    for j in range(n):
        m=(i+j)%3
        cij=c[i][j]
        if cij in mods[m].keys():mods[m][cij]+=1
        else:mods[m][cij]=1
mins=[[],[],[]]
for i in range(b):
    for l in [0,1,2]:mins[l]+=[sum([d[k-1][i]*v for(k,v)in mods[l].items()])]
r=1000000
for i in range(b):
    for j in range(b):
        for k in range(b):
            if i!=j and j!=k and k!=i:
                r=min(mins[0][i]+mins[1][j]+mins[2][k],r)
print(r)

Submission status: Wrong Answer

Solution code:
import random
from itertools import product

N, C = map(int, input().split())
D = []
for _ in range(C):
    D.append(list(map(int, input().split())))
cost = {}
for i, j in product(range(C), range(C)):
    cost[(i+1, j+1)] = D[i][j]

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

a0 = []
a1 = []
a2 = []

for i, j in product(range(N), range(N)):
    if i+j % 3 == 0:
        a0.append(c[i][j])
    elif i+j % 3 == 1:
        a1.append(c[i][j])
    elif i+j % 3 == 2:
        a2.append(c[i][j])

def paint(a0, a1, a2, x, y, z):
    ans = 0
    ans += sum([cost[(a, x)] for a in a0])
    ans += sum([cost[(a, y)] for a in a1])
    ans += sum([cost[(a, z)] for a in a2])
    return ans


ans = N**2 * 1000
for _ in range(10000):
    C_list = list(range(1, C+1))
    random.shuffle(C_list)
    x, y, z = C_list[:3]
    ans = min(ans, paint(a0, a1, a2, x, y, z))

print(ans)

Submission status: Wrong Answer

Solution code:
s=input().split()
N=int(s[0])
C=int(s[1])
d=[]
for i in range(C):
    s=input().split()
    temp=[]
    for item in s:
        temp.append(int(item))
    d.append(temp)
if N==1:
    print("0")
else:
    c=[[],[],[]]
    cost=[[],[],[]]
    for j in range(N):
        s=input().split()
        for i in range(len(s)):
            c[(i+j)%3].append(int(s[i])-1)
    for i in range(C):
        s=0
        for col in c[0]:
            s+=d[col][i]
        cost[0].append((s,i))
        s=0
        for col in c[1]:
            s+=d[col][i]
        cost[1].append((s,i))
        s=0
        for col in c[2]:
            s+=d[col][i]
        cost[2].append((s,i))
    cost[0].sort()
    cost[1].sort()
    cost[2].sort()
    res=3000000
    for i in range(3):
        for j in range(3):
            for k in range(3):
                if cost[0][i][1]!=cost[1][j][1] and cost[1][j][1]!=cost[2][k][1] and cost[2][k][1]!=cost[0][i][1]:
                    res=min(res,cost[0][i][0]+cost[1][j][0]+cost[2][k][0])
    print(res)

Submission status: Wrong Answer

Solution code:
N,C = list(map(int,(input()).split()))
Dlist = []
clist = []

for i in range(C):
	Dlist.append(list(map(int,(input()).split())))

for i in range(N):
	clist.append(list(map(int,(input()).split())))

iwakan = [[],[],[]]

for k in range(C):
	iwakanTemp = [0,0,0]
	for i in range(N):
		for j in range(N):
			iwakanTemp[(i + j) % 3] += Dlist[clist[i][j]-1][k]

	
	for i in range(3):
		iwakan[i].append(iwakanTemp[i])


sumTemp = 11451419
for i in range(C):
	for j in range(C):
		for k in range(C):
			if not (i-j)*(j-k)*(k-i) == 0:
				hoge = iwakan[0][i]+iwakan[1][j]+iwakan[2][k]
				if hoge < sumTemp:
					sumTemp = hoge

print(sumTemp)

Submission status: Wrong Answer

Solution code:
N,C = [int(i) for i in input().split()]
D = [[int(j) for j in input().split()] for i in range(C)]
c = [[int(j) for j in input().split()] for i in range(N)]
bank = [[],[],[]]
for i in range(N):
    for j in range(N):
        bank[(i+j)%3].append(c[i][j]-1)

C = [ii for ii in range(C)]
min = 100000
for i in C:
    for j in C:
        if j != i:
            for k in C:
                if k != i and k != j:
                    count = 0
                    count += sum([D[x][i] for x in bank[0] if x != i])
                    count += sum([D[y][j] for y in bank[1] if y != j])
                    count += sum([D[z][k] for z in bank[2] if z != k])
                    if min > count:
                        min = count
print(min)

Submission status: Wrong Answer

Solution code:
import numpy as np
N, C = map(int, input().split(' '))
diff = [list(map(int, input().split(' '))) for _ in range(C)]
tiles = [[0 for _ in range(C)] for _ in range(3)]
r = 2
for i in range(N):
    tmp = list(map(int, input().split(' ')))
    for j, c in enumerate(tmp):
        tiles[(r+j)%3][c-1] += 1
    r = (r + 1) % 3

iwakan = np.dot(np.array(tiles), np.array(diff))
iwakan[np.where(iwakan == 0)] = 1000000

res = float('INF')
for i in range(C):
    for j in range(C):
        for k in range(C):
            if i != j and j != k and k != i:
                res = min(res, iwakan[0][i] + iwakan[1][j] + iwakan[2][k])
print(res)

Submission status: Wrong Answer

Solution code:
from itertools import *
N, C = map(int, input().split())
D = [list(map(int, input().split())) for _ in [0]*C]
c = [list(map(int, input().split())) for _ in [0]*N]
tri = [[] for _ in [0]*3]
for i in range(1, N+1):
    for j in range(1, N+1):
        tri[(i+j) % 3] += [c[i-1][j-1] - 1]
incom = [[0]*C for _ in [0]*3]
for i in range(3):
    for color in range(C):
        incom[i][color] = sum(D[x][color] for x in tri[i])
ans = 1<<30
for p in permutations(range(3), 3):
    t = sum(incom[x][y]for x,y in enumerate(p))
    if t < ans: ans = t
print(ans)

Submission status: Wrong Answer

Solution code:
# D
import numpy as np

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

C_cost_mat = np.zeros((C, C), dtype="int32")
now_mat = np.zeros((3, C), dtype="int32")

for i in range(C):
    c_list = list(map(int, input().split()))
    for j in range(C):
        C_cost_mat[i][j] = c_list[j]
        
for i in range(N):
    c_list = list(map(int, input().split()))
    for j in range(N):
        now_mat[(i + j + 2) % 3, c_list[j] - 1] += 1
        
res_mat = np.dot(now_mat, C_cost_mat)

res = 3000
for i1 in range(C):
    for i2 in range(C):
        for i3 in range(C):
            if i1 != i2 and i2 != i3 and i3 != i1:
                res = min(res, res_mat[0, i1] + res_mat[1, i2] + res_mat[2, i3])
print(res)

Submission status: Wrong Answer

Solution code:
N,C = map(int, input().split())
x = 1000000
y = 0
D = [list(map(int,input().split())) for l in range(C)]
c = [list(map(int,input().split())) for l in range(N)]
for i in range(1,C+1):
    for j in range(1,C+1):
        if j == i:
            continue
        for k in range(1,C+1):
            if k ==i or k == j:
                continue
            for l in range(N):
                if y > x:
                    break
                for m in range(N):
                    if y > x:
                        break
                    if (l+m)%3 == 0:
                        y += D[c[l][m]-1][i-1]
                    if (l+m)%3 == 1:
                        y += D[c[l][m]-1][j-1]
                    if (l+m)%3 == 2:
                        y += D[c[l][m]-1][k-1]
                    
            x = min(x,y)
            y = 0
print(x)

Submission status: Wrong Answer

Solution code:
n,c=map(int,input().split())
Ds = [list(map(int,input().split())) for x in range(c)]
colors = [list(map(int,input().split())) for x in range(n)]
count0,count1,count2 = [0]*c,[0]*c,[0]*c
for i in range(n):
  for j in range(n):
    if (i+j)%3 == 0:
      count0[colors[i][j]-1] += 1
    elif (i+j)%3 == 1:
      count1[colors[i][j]-1] += 1
    else:
      count2[colors[i][j]-1] += 1
total = pow(10,8)
for a in range(c):
  for b in range(c):
    for d in range(c):
      if a == b or b == d or d == a:
        continue
      tmp = 0
      for x in range(c):
        tmp += count0[x]*Ds[x][a]+count1[x]*Ds[x][b]+count2[x]*Ds[x][d]
      total = min(total,tmp)
print(total)

Submission status: Wrong Answer

Solution code:
import numpy as np
N, C = map(int, input().split(' '))
diff = [list(map(int, input().split(' '))) for _ in range(C)]
tiles = [[0 for _ in range(C)] for _ in range(3)]
r = 2
for i in range(N):
    tmp = list(map(int, input().split(' ')))
    for j, c in enumerate(tmp):
        tiles[(r+j)%3][c-1] += 1
    r = (r + 1) % 3

iwakan = np.dot(np.array(tiles), np.array(diff))
iwakan[np.where(iwakan == 0)] = 1000000
min_diff = np.min(iwakan, axis=0)

print(np.sum(min_diff))

Submission status: Wrong Answer

Solution code:
N,C = map(int, input().split())
x = 1000000
y = 0
D = [list(map(int,input().split())) for l in range(C)]
c = [list(map(int,input().split())) for l in range(N)]
print(D)
for i in range(1,C+1):
    for j in range(1,C+1):
        if j == i:
            continue
        for k in range(1,C+1):
            if k ==i or k == j:
                continue
            for l in range(N):
                for m in range(N):
                    if (l+m)%3 == 0:
                        y += D[c[l][m]-1][i-1]
                    if (l+m)%3 == 1:
                        y += D[c[l][m]-1][j-1]
                    if (l+m)%3 == 2:
                        y += D[c[l][m]-1][k-1]
            x = min(x,y)
            y = 0
print(x)

Submission status: Wrong Answer

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

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

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

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

minCount = 100000
sum1 = sum(e[0])
sum2 = sum(e[1])
sum3 = sum(e[2])

for i in range(1, C + 1):
    cost1 = 0
    for h in range(1, C + 1):
        if i == h:
            continue
        cost1 += d[h - 1][i - 1] * e[0][h]

    for j in range(1, C + 1):

        if i == j:
            continue
        cost2 = 0
        for h in range(1, C + 1):
            if j == h:
                continue
            cost2 += d[h - 1][j - 1] * e[1][h]

        for k in range(1, C + 1):

            if j == k or k == i:
                continue

            cost3 = 0
            for h in range(1, C + 1):
                if k == j:
                    continue
                cost3 += d[h - 1][k - 1] * e[2][h]

            minCount = min(minCount, cost1 + cost2 + cost3)

print(minCount)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!


n,b=map(int,input().split())
d=[list(map(int,input().split()))for _ in[0]*b]
dm=[min(d[i])for i in range(b)]
c=[list(map(int,input().split()))for _ in[0]*n]
m0,m1,m2={},{},{}
for i in range(n):
    for j in range(n):
        m=(i+j)%3
        cij=c[i][j]
        if m==0:
            if cij in m0:m0[cij]+=1
            else:m0[cij]=1
        elif m==1:
            if cij in m1:m1[cij]+=1
            else:m1[cij]=1
        else:
            if cij in m2:m2[cij]+=1
            else:m2[cij]=1
min0,min1,min2=[],[],[]
for i in range(b):
    min0+=[sum([d[k-1][i]*v for(k,v)in m0.items()])]
    min1+=[sum([d[k-1][i]*v for(k,v)in m1.items()])]
    min2+=[sum([d[k-1][i]*v for(k,v)in m2.items()])]
r=1000000
for i in range(b):
    for j in range(b):
        for k in range(b):
            if i!=j and j!=k and k!=i:
                r=min(min0[i]+min1[j]+min2[k],r)
print(r)

Submission status: Wrong Answer

Solution code:
N,C = [int(i) for i in input().split()]
D = [[int(j) for j in input().split()] for i in range(C)]
c = [[int(j) for j in input().split()] for i in range(N)]
bank = [[],[],[]]
for i in range(N):
    for j in range(N):
        bank[(i+j)%3].append(c[i][j]-1)


min = 100000
for i in [ii for ii in range(C)]:
    for j in [jj for jj in range(C) if jj != i]:
        for k in [kk for kk in range(C) if kk != i and kk != j]:
            count = 0
            #for x in bank[0]:
            #    if x != i:
            #        count += D[x][i]
            count += sum([D[x][i] for x in bank[0] if x != i])
            count += sum([D[y][j] for y in bank[1] if y != j])
            count += sum([D[z][k] for z in bank[2] if z != k])

            #for y in bank[1]:
            #    if y != j:
            #        count += D[y][j]
            #for z in bank[2]:
            #    if z != k:
            #        count += D[z][k]
            if min > count:
                min = count
print(min)

Submission status: Wrong Answer

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

X0,X1,X2 = [],[],[]
for i in range(N):
    for j in range(N):
        if (i+j)%3 == 0:
            X0.append(A[i][j])
        elif (i+j)%3 == 1:
            X1.append(A[i][j])
        else:
            X2.append(A[i][j])

# それぞれの集合を塗り替える場合のコストを計算
Xn = [X0,X1,X2]
cost = [[0 for _ in range(C)] for _ in range(3)]
for i in range(3):
    for c in range(1,C+1):
        Ans = 0
        for x in Xn[i]:
            if x != c:
                Ans += D[x-1][c-1]
        cost[i][c-1] = Ans

Y0 = cost[0][0:3]
Y1 = cost[1][0:3]
Y2 = cost[2][0:3]
Ans = 1000000000000000
for i in range(3):
    for j in range(3):
        for k in range(3):
            if i != j and j != k and k != i:
                Ans = min(Ans, Y0[i]+Y1[j]+Y2[k])

print(Ans)

Submission status: Wrong Answer

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

ans_A = 0
for i in range(N):
    for j in range(N):
        ans_A += min(D[c[i][j]-1][(i+j+2)%3::3])

ans_B = 0
for i in range(N):
    for j in range(N):
        ans_B += min(D[c[i][j]-1][(i+j+3)%3::3])

ans_C = 0
for i in range(N):
    for j in range(N):
        ans_C += min(D[c[i][j]-1][(i+j+1)%3::3])

print(min(ans_A, ans_B, ans_C))

Submission status: Wrong Answer

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

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

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

ans_C = 0
for i in range(N):
    for j in range(N):
        ans_C += D[c[i][j]-1][(i+j+1)%3]
        #print(D[c[i][j]-1][(i+j+2)%3-1])
print(min(ans_A, ans_B, ans_C))

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import numpy as np
N, C = map(int, input().split())
D = np.ndarray((C, C), dtype=int)
c = np.ndarray((N, N), dtype=int)
for i in range(C):
    D[i] = list(map(int,input().split()))
for i in range(N):
    c[i] = list(map(int,input().split()))
c -= 1
acc = [[0]*C for _ in range(3)]
for i in range(N):
    for j in range(N):
        for k in range(C):
            acc[(i+j) % 3][k] += D[c[i][j]][k]
ans = float("inf")
for i,j,k in permutations(range(C), r=3):
    ans = min(ans, acc[0][i]+acc[1][j]+acc[2][k])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
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)]
acc = [[0]*C for _ in range(3)]
for i in range(N):
    for j in range(N):
        for k in range(C):
            acc[(i+j) % 3][k] += D[c[i][j]-1][k]
ans = float("inf")
for i,j,k in permutations(range(C), r=3):
    ans = min(ans, acc[0][i]+acc[1][j]+acc[2][k])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, copy,bisect
from operator import itemgetter
from heapq import heappush, heappop
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

stdin = sys.stdin

ni = lambda: int(ns())
nf = lambda: float(ns())
na = lambda: list(map(int, stdin.readline().split()))
nb = lambda: list(map(float, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

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

z = []
o = []
t = []
for i in range(1, N+1):
    for j in range(1, N+1):
        q = (i + j) % 3
        if q == 0:
            z.append(c[i-1][j-1] - 1)
        if q == 1:
            o.append(c[i-1][j-1] - 1)
        if q == 2:
            t.append(c[i-1][j-1] - 1)

ans = inf
for i, j, k in itertools.permutations(range(C), 3):
    tmp = 0
    for num in z:
        tmp += D[num][i]
    for num in o:
        tmp += D[num][j]
    for num in t:
        tmp += D[num][k]
    ans = min(tmp, ans)
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)]
sum_val = [[0] * C for _ in range(3)]

for color in range(1, C + 1):
    for i in range(N):
        for j in range(N):
            sum_val[(i + j) % 3][color - 1] += D[c[i][j] - 1][color - 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
            ans = min(ans, sum_val[0][i] + sum_val[1][j] + sum_val[2][k])
print(ans)

Submission status: Time Limit Exceeded

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

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


ans = min(
    sum(cost[c][i] for i, c in enumerate(colors))
    for colors in permutations(range(C), 3)
)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations, 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)]

ans = float("inf")
for colors in combinations(range(C), 3):
    for p_colors in permutations(colors):
        tmp = 0
        for i in range(N):
            for j in range(N):
                c_color = c[i][j] - 1
                n_color = p_colors[(i + j) % 3]
                if c_color == n_color:
                    continue
                tmp += D[c_color][n_color]
        ans = min(ans, tmp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
#D - Good Grid
import sys 
from itertools import permutations
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N,C = map(int,readline().split())
D = []
for _ in range(C):
    row = list(map(int,readline().split()))
    D.append(row)
data = []
for _ in range(N):
    row = list(map(int,readline().split()))
    data.append(row)

INF = 10**31
ans = INF
A = [i for i in range(C)]

for a,b,c in permutations(A,3):
    total = 0
    for i in range(N):
        for j in range(N):
            pre_c = data[i][j]-1
            if (i+j) % 3 == 0:
                total += D[pre_c][a]   
            elif (i+j) % 3 == 1:
                total += D[pre_c][b]
            else:
                total += D[pre_c][c]
    ans = min(ans,total)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
INF = float("inf")
N,C=map(int, input().split())
D=[[INF]*(C+1) for _ in range(C+1)]
c = [[-1]*(N+1) for _ in range(N+1)]
for i in range(1, C+1):
    tmp=list(map(int, input().split()))
    for j in range(1, C+1):
        D[i][j] = tmp[j-1]
for i in range(1, N+1):
    tmp=list(map(int, input().split()))
    for j in range(1, N+1):
        c[i][j] = tmp[j-1]
res0 = []
res1 = []
res2 = []
for i in range(1, N+1):
    for j in range(1, N+1):
        if (i+j)%3==0:
            res0.append((i,j))
        elif (i+j)%3==1:
            res1.append((i,j))
        else:
            res2.append((i,j))
ans = INF
for c0, c1, c2 in permutations(range(1, C+1), 3):
    disgust = 0
    for i, j in res0:
        disgust += D[c[i][j]][c0]
    for i, j in res1:
        disgust += D[c[i][j]][c1]
    for i, j in res2:
        disgust += D[c[i][j]][c2]
    ans = min(ans, disgust)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#! /usr/bin/env python3
import itertools
import sys
sys.setrecursionlimit(10**9)


INF=10**20
def solve(N: int, C: int, D: "List[List[int]]", c: "List[List[int]]"):

    colormap = [[] for _ in range(3)]
    for i in range(1,N+1):
        for j in range(1,N+1):
            k = i+j
            k %= 3
            colormap[k].append(c[i-1][j-1])

    ans = INF
    for _colors in itertools.permutations(list(range(1,C+1)),3):
        colors = list(_colors)
        res = 0
        for mod,current_colors in enumerate(colormap):
            for current in current_colors:
                color = colors[mod]
                res += D[current-1][color-1]

        ans = min(res,ans)

    
    print(ans)

    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # 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:
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)]

group0,group1,group2=[],[],[]

for i in range(n):
  for j in range(n):
    if (i+j+2)%3==0:
      group0.append([i,j,C[i][j]-1])
    elif (i+j+2)%3==1:
      group1.append([i,j,C[i][j]-1])
    elif (i+j+2)%3==2:
      group2.append([i,j,C[i][j]-1])

ans=float('inf')


for xxx,yyy,zzz in itertools.permutations(range(c),3):
  cnt=0
  for i in group0:
    if i[2]!=xxx:
      cnt+=D[i[2]][xxx]
  for i in group1:
    if i[2]!=yyy:
      cnt+=D[i[2]][yyy]
  for i in group2:
    if i[2]!=zzz:
      cnt+=D[i[2]][zzz]
  
  ans=min(ans,cnt)


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, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

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

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

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


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


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

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

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,C=map(int,input().split())
d=[]
c=[]
ans=float("inf")
for i in range(C):
    d.append(list(map(int,input().split())))
for i in range(n):
    c.append(list(map(int,input().split())))
for i in range(1,C+1):
    for j in range(1,C+1):
        if i==j:
            continue
        for k in range(1,C+1):
            if k==i or k==j:
                continue
            t=0
            for ii in range(n):
                for jj in range(n):
                    z=(ii+jj+2)%3
                    if z==0:
                        t+=d[c[ii][jj]-1][i-1]
                    elif z==1:
                        t+=d[c[ii][jj]-1][j-1]
                    elif z==2:
                        t+=d[c[ii][jj]-1][k-1]
            if t<ans:
                ans=t
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

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

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

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

ans = 10**10
for cp in cpl:
    cost = 0
    for i in range(n):
        for j in range(n):
            val3 = (i+j+2)%3
            target_c = cp[val3]
            orig_c = cl[i][j]-1
            cost += dl[orig_c][target_c]
    ans = min(ans,cost)

print(ans)

Submission status: Time Limit Exceeded

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

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


ans = 10 ** 10
for i in range(1,c**3):
    x=i%c
    y=(i%c**2)//c
    z=i//c**2
    if x==y or y==z or z==x:
        continue
    else:
        color=[x,y,z]
        count = 0
        for a in range(n):
            for b in range(n):
                if color[(a+b+2)%3] != c_list[b][a]-1:
                    count+=D_list[c_list[b][a]-1][color[(a+b+2)%3]]
        if count < ans:
            ans = count

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
N, C = map(int, input().split())

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

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

ans = 10**12

# 塗り分けの順列総数
for p in permutations(range(C),3):
    tmp = 0
    for i in range(N):
        if tmp > ans:
            break
        for j in range(N):
            tmp += D[c[i][j]-1][p[(i+j)%3]]
    ans = min(ans,tmp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

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

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

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

ans = 10**12

# 塗り分けの順列総数
for p in permutations(range(C),3):
    tmp = 0
    for i in range(N):
        for j in range(N):
            tmp += D[c[i][j]-1][p[(i+j)%3]]
    ans = min(ans,tmp)

print(ans)