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 _ in range(C)]
c=[list(map(int, input().split())) for _ in range(N)]

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

ans=1000*500*500
for i in range(C):
    for j in filter(lambda x:x!=i,range(C)):
        for k in filter(lambda x:x!=i and x!=j, range(C)):
            #print(cost[0][i]+cost[1][j]+cost[2][k])
            ans=min(cost[0][i]+cost[1][j]+cost[2][k], ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    #0. input
#    N,C = 2, 3
#    D = [[0, 1, 1], [1, 0, 1], [1, 4, 0]] 
#    c_init = [[1, 2],[3, 3]]
    
#    N, C = 4, 3
#    D = [[0, 12, 71],
#             [81, 0, 53],
#             [14, 92, 0]]
#    c_init = [[1, 1, 2, 1],
#                   [2, 1, 1, 2],
#                   [2, 2, 1, 3],
#                   [1, 1, 2, 2]]
    
    N, C = map(int, input().split())
    
    D = []
    for i in range(C):
        D.append(list(map(int,input().split())))
        
    c_init = []
    for i in range(N):
        c_init.append(list(map(int, input().split())))
    
    iwakan = []
    
    for color0 in range(C):
        
        for color1 in range(C):
            if color1 == color0:
                continue
            
            for color2 in range(C):
                if color2 == color0 or color2 == color1:
                    continue
                
                # calculate diff
                iwakan_temp = 0
                for i in range(N):
                    for j in range(N):
                        if (i+j)%3 == 0:
                            iwakan_temp += D[c_init[i][j] - 1][color0 - 1]
                        elif (i+j)%3 == 1:
                            iwakan_temp += D[c_init[i][j] - 1][color1 - 1]
                        else:
                            iwakan_temp += D[c_init[i][j] - 1][color2 - 1]
                            
                iwakan.append(iwakan_temp)
                
    ans = min(iwakan)
    print(ans)
                


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
lngN, lngC = map(int, input().split())

##  lstD[x][y]
##  1 オリジン の C × C グリッド として扱うために、[False] * lngC を第一行と第一列に追加
##  x -> y に塗り替えたときの違和感
##  x, y: 0 ... lngC - 1
lstD = []
lstD.append([False] * lngC)
for i in range(lngC):
    lstD.append([False] + list(map(int, input().split())))
##  lstC[i][j]
##  1 オリジン の N × N グリッド として扱うために、[False] * lngN を第一行と第一列に追加
##  マス(i, j)の初期色
##  1 から C までの値を取る
lstC = []
lstC.append([False] * lngN)
for i in range(lngN):
    lstC.append([False] + list(map(int, input().split())))
##  lstDSum[r][c]
##  剰余 r のグループを 色 c で塗るときの違和感の和
##　[c]を 1 オリジン として扱うために、[False] * lngC を第一行に追加
##  r: 0, 1, 2
##  c: 1 ... lngC
lstDSum = [False] * 3
for r in range(3):
    lstDSum[r] = [False] * (lngC + 1)
    for c in range(1, lngC + 1):
        lstDSum[r][c] = 0##違和感の初期値

for i in range(1, lngN + 1):
    for j in range(1, lngN + 1):
        for c in range(1, lngC + 1):
            r = (i + j) % 3##　剰余
            oriC = lstC[i][j]##初期色
            lstDSum[r][c] += lstD[oriC][c]

ans = float('inf')
for i in range(1, lngC + 1):
    for j in range(1, lngC + 1):
        if (i != j):
            for k in range(1, lngC + 1):
                if (i != k) and (j != k):
                    ans = min(ans, lstDSum[0][i] + lstDSum[1][j] + lstDSum[2][k])
print(ans)

##グリッドのマス(i, j)とすると,
##(i + j) % 3 の値によって, マスは 3 グループに分かれる (0, 1, 2)

##各グループの色分けの仕方は, itertools.permutations(c, 3) 通り
##内訳は次の通り
    ##(0)色 1 から C までの C 通りに色分け
    ##(1)色 1 から C までの (C - 1) 通りに色分け ((0) 分を除外)
    ##(2)色 1 から C までの (C - 2) 通りに色分け ((0, 1) 分を除外)

##各グループについて
##色 1 から C までの C 通りに色分けしたときの違和感の和を配列化
##lstDSum[グループ番号][色]
    ##グループ番号: 0, 1, 2
    ##色: 1 から C まで

##for 文で, 各グループを塗る色を全探索
##(グループ番号, 色) = (0, i), (1, j), (2, k)とするときの違和感の和
##lstDSum[0][i] + lstDSum[1][j] + lstDSum[2][k]
##これの最小値を取ればよい

Submission status: Time Limit Exceeded

Solution code:
lngN, lngC = map(int, input().split())

##  lstD[x][y]
##  C×C
##  x -> y に塗り替えたときの違和感
##  x, y: 0 ... lngC - 1
##  x == y: 0
##  x != y: 1 から 1000 の値を取る
lstD = []
for i in range(lngC):
    lstD.append(list(map(int, input().split())))
##  lstC[i][j]
##  N×N
##  マス(i, j)の初期色
##  1 から C までの値を取る
lstC = []
for i in range(lngN):
    lstC.append(list(map(int, input().split())))
##  lstDSum[r][c]
##  剰余 r のグループを 色 c で塗るときの違和感の和
##  r: 0, 1, 2
##  c: 1 ... lngC
lstDSum = dict()
for r in range(3):
    lstDSum[r] = dict()
    for c in range(1, lngC + 1):
        lstDSum[r][c] = 0##違和感の初期値

for i in range(lngN):
    for j in range(lngN):
        for c in range(1, lngC + 1):
            ##　剰余
            ##　配列は 0 オリジンで, グリッドは 1 オリジンなので,
            ##　配列の座標 i, j から グリッドの座標に変換するために, i, j に 1 足した（意味はない）
            r = ((i + 1) + (j + 1)) % 3
            oriC = lstC[i][j]##初期色
            ##　lstD[初期色][塗り替えた後の色] で 色は, 0 ... lngC - 1までの値を取る
            ##　oriC, cは共に 1 ... lngC までの値を取るので, 1 減らす必要がある
            lstDSum[r][c] += lstD[oriC - 1][c - 1]            

ans = float('inf')
for i in range(1, lngC + 1):
    for j in range(1, lngC + 1):
        if (i != j):
            for k in range(1, lngC + 1):
                if (i != k) and (j != k):
                    ans = min(ans, lstDSum[0][i] + lstDSum[1][j] + lstDSum[2][k])
print(ans)

##グリッドのマス(i, j)とすると,
##(i + j) % 3 の値によって, マスは 3 グループに分かれる (0, 1, 2)

##各グループの色分けの仕方は, itertools.permutations(c, 3) 通り
##内訳は次の通り
    ##(0)色 1 から C までの C 通りに色分け
    ##(1)色 1 から C までの (C - 1) 通りに色分け ((0) 分を除外)
    ##(2)色 1 から C までの (C - 2) 通りに色分け ((0, 1) 分を除外)

##各グループについて
##色 1 から C までの C 通りに色分けしたときの違和感の和を配列化
##lstDSum[グループ番号][色]
    ##グループ番号: 0, 1, 2
    ##色: 1 から C まで

##for 文で, 各グループを塗る色を全探索
##(グループ番号, 色) = (0, i), (1, j), (2, k)とするときの違和感の和
##lstDSum[0][i] + lstDSum[1][j] + lstDSum[2][k]
##これの最小値を取ればよい

Submission status: Time Limit Exceeded

Solution code:
N, C = map(int, input().split())
#D[X][Y] = (X+1)→(Y+1)に塗り替えたときの違和感
D = [list(map(int, input().split())) for i in range(C)]
#C[i][j] = (i+1,j+1)の色
c = [list(map(int, input().split())) for i in range(N)]
#import pdb; pdb.set_trace()
ans = float('inf')

def mult3(x):
    if x % 3 == 0:
        return 1
    else:
        return 0

for x in range(C):
    for y in range(C):
        for z in range(C):
            if (x-y)*(y-z)*(z-x) != 0:
                new_grid = [[mult3(i+j) * x + mult3(i+j-1) * y + mult3(i + j -2) * z + 1 for j in range(N)]for i in range(N)]
                iwakan = 0
                for i in range(N):
                    for j in range(N):
                        iwakan += D[c[i][j] - 1][new_grid[i][j] - 1]
                ans = min(ans, iwakan)
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 i in range(C)] 
c = [list(map(int, input().split()))  for i in range(N)] 

# 3行にまとめる
c_listed = [[],[],[]]

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



# 色の選び方
color_seq = permutations(range(C), 3)

ret = N * N * 1000
for color in color_seq:
    count = 0
    for line, line_color in zip(c_listed, color):
        for f in line:
            # f to line_color
            count += d[f-1][line_color]

    # 
    if count < ret:
        ret = count

print(ret)

Submission status: Time Limit Exceeded

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

cost = [[0]*C for _ in range(3)]
for i in range(C):
    for a in range(N):
        for b in range(N):
            cost[(a+b)%3][i] += D[G[a][b]-1][i]

ans = 10**10
for i in range(C):
    for j in range(C):
        for k in range(C):
            if i == j or j == k or k == i:
                pass
            else:
                ans = min(ans, cost[0][i] + cost[1][j] + cost[2][k])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,c = map(int,input().split())
d = [list(map(int,input().split())) for i in range(c)]
g = [list(map(int,input().split())) for i in range(n)]
# mod=0,1,2について、色iに変えた時のコストをまとめておく
cost = [[0]*c for i in range(3)]
for i in range(3):
    for j in range(c):
        cost[i][j] = sum([d[g[a][b]-1][j] for a in range(n) for b in range(n) if (a+b)%3==i])
# mod=0,1,2について、どの色で塗るか全探索
ret=10**10
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
            ret=min(ret, cost[0][i]+cost[1][j]+cost[2][k])
print(ret)

Submission status: Time Limit Exceeded

Solution code:
n,c = map(int,input().split())
d = [list(map(int,input().split())) for i in range(c)]
g = [list(map(int,input().split())) for i in range(n)]
# mod=0,1,2について、色iに変えた時のコストをまとめておく
cost = [[0]*c for i in range(3)]
for i in range(3):
    for j in range(c):
        for a in range(n):
            for b in range(n):
                if (a+b)%3==i:
                    cost[i][j]+=d[g[a][b]-1][j]
# mod=0,1,2について、どの色で塗るか全探索
ret=10**10
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
            ret=min(ret, cost[0][i]+cost[1][j]+cost[2][k])
print(ret)

Submission status: Time Limit Exceeded

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

change = [[0]*C for i in range(3)]
for c in range(C):
    for i in range(1, N+1):
        for j in range(1, N+1):
            change[(i+j) % 3][c] += (D[G[i-1][j-1]-1][c] if G[i-1][j-1] != c+1 else 0)

ans = float('inf')
for c1 in range(C):
    for c2 in range(C):
        for c3 in range(C):
            if len(set((c1, c2, c3))) != 3:
                continue
            ans = min(ans, change[0][c1] + change[1][c2] + change[2][c3])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, C = list(map(int, input().split()))
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
D0 = {}
D1 = {}
D2 = {}
for color in range(1, C + 1):
    D0[color] = 0
    D1[color] = 0
    D2[color] = 0
    
for color in range(1, C + 1):
    for i in range(N):
        for j in range(N):
            if (i + j) % 3 == 0:
                D0[color] = D0[color] + D[ c[i][j] - 1 ][ color - 1 ] 
            if (i + j) % 3 == 1:
                D1[color] = D1[color] + D[ c[i][j] - 1 ][ color - 1 ] 
            if (i + j) % 3 == 2:
                D2[color] = D2[color] + D[ c[i][j] - 1 ][ color - 1 ] 

ans = 1000000000000000
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:
                tmp = D0[i] + D1[j] + D2[k]
                if tmp < ans:
                    ans = tmp
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 i in range(c)]
C = [list(map(int, input().split())) for i in range(n)]
zero = []
one = []
two = []
ans = float('Inf')
for i in range(n):
  for j in range(n):
    if (i + j) % 3 == 0:
      zero.append(C[i][j])
    elif (i + j) % 3 == 1:
      one.append(C[i][j])
    elif (i + j) % 3 == 2:
      two.append(C[i][j])

combo = list(permutations(range(0,c), 3))


for a, b, c in combo:
  temp = 0
  
  for v in zero:
    temp += D[v-1][a]
  for v in one:
    temp += D[v-1][b]
  for v in two:
    temp += D[v-1][c]

  ans = min(ans, temp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import functools
from itertools import permutations


@functools.lru_cache(maxsize=None)
def cost1(i, color):
    cost = 0
    for r in range(N):
        for c in range(N):
            if (r + c) % 3 == i:
                cost += D[G[r][c] - 1][color - 1]

    return cost


def cost2(comb):
    cost = 0
    for i, color in enumerate(comb):
        cost += cost1(i, color)

    return cost


N, C = map(int, input().split())
D = [[int(_) for _ in input().split()] for i in range(C)]
G = [[int(_) for _ in input().split()] for i in range(N)]
combs = permutations(range(1, C + 1), 3)
min_cost = min([cost2(comb) for comb in combs])
print(min_cost)

Submission status: Time Limit Exceeded

Solution code:
N,C = map(int,input().split())
D=[[int(i) for i in input().split()] for j in range(C)]
co=[[int(i) for i in input().split()] for j in range(N)]
A=[[0]*C for i in range(3)]#iに変えた時の違和感
for i in range(N):
    for j in range(N):
        t = (i+j)%3
        for s in range(C):
            A[t][s]+=D[co[j][i]-1][s]
ans =10**13
for x in range(C):
    for y in range(C):
        if x==y:
            continue
        for z in range(C):
            if x==z or y==z:
                continue
            ans=min(ans,A[0][x]+A[1][y]+A[2][z])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools  import product, permutations

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

res = 1000*N*N

scores = [[0,0,0] for _ in range(C)]

for cc in range(C):
    for i,j in product(range(N), range(N)):
        if (i + j)%3 == 0:
            scores[cc][0] += D[c[i][j]][cc]
        if (i + j)%3 == 1:
            scores[cc][1] += D[c[i][j]][cc]
        if (i + j)%3 == 2:
            scores[cc][2] += D[c[i][j]][cc]



for c1, c2, c3 in permutations(range(C), 3):
    score = scores[c1][0] + scores[c2][1] + scores[c3][2]
    if res > score:
        res = score

print(res)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

D = np.zeros((C,C), dtype=int)

for i in range(C):
    D[i] = np.array(input().split())

c = np.zeros((N,N), dtype=int)

for i in range(N):
    c[i] = np.array(input().split())

c -= 1

res = 1000*N*N

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
            score = 0
            for i in range(N):
                for j in range(N):
                    if (i + j)%3 == 0:
                        cc = c1
                    if (i + j)%3 == 1:
                        cc = c2
                    if (i + j)%3 == 2:
                        cc = c3

                    score += D[c[i][j]][cc]

            if res > score:
                res = score

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)]
space = [list(map(int,input().split())) for _ in range(N)]
c = [[0 for j in range(C)]for i in range(3)]

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

#3色選んで違和感を求める
Iwakan = 1e+10
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
            tmp_Iwakan = c[0][i]+c[1][j]+c[2][k]
            Iwakan = min(Iwakan,tmp_Iwakan)

print(Iwakan)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n,c = map(int,input().split())

cost = []

for i in range(c):
    cost.append(list(map(int,input().split())))

arr = []

for i in range(n):
    arr.append(list(map(int,input().split())))

arr = np.array(arr)

sparr = [[],[],[]]

for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        if (i+j+2) %3 == 0:
            sparr[0].append(arr[i][j])
        elif (i+j+2) %3 == 1:
            sparr[1].append(arr[i][j])
        else:
            sparr[2].append(arr[i][j])

out = 0

kouho = [[],[],[]]
for i in range(3):
    for j in range(c):
        temp = 0
        for line in sparr[i]:
            temp += cost[line-1][j]
        kouho[i].append(temp)

min = 100000000000

for i in range(c):
    for j in range(c):
        for k in range(c):
            if i != j and j != k and i != k and kouho[0][i] + kouho[1][j] + kouho [2][k] < min:
                min = kouho[0][i] + kouho[1][j] + kouho [2][k]

print(min)

Submission status: Time Limit Exceeded

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

for i in range(N):
    tmp = list(map(int,input().split()))
    for j in range(N):
        for k in range(C):
            c[(i+j+2)%3][k] += D[tmp[j]-1][k]

#3色選んで違和感を求める
Iwakan = 1e+10
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
            tmp_Iwakan = c[0][i]+c[1][j]+c[2][k]
            Iwakan = min(Iwakan,tmp_Iwakan)

print(Iwakan)

Submission status: Time Limit Exceeded

Solution code:
N,C=[int(i) for i in input().split()]
D = [[int(i) for i in input().split()] for j in range(C)]
color=[[int(i) for i in input().split()] for j in range(N)]
#N,C=2,3
#D=[[0,1,1],[1,0,1],[1,4,0]]
#color=[[1,2],[3,3]]
Dsum= [[0 for i in range(C)] for j in range(C)]
a=1145148101919
for c in range(C):
    
    for i in range(N):
        for j in range(N):
            Dsum[c][(i+j+2)%3]=Dsum[c][(i+j+2)%3]+D[color[i][j]-1][c]
#            print(Dsum)

for c0 in range(C):
    for c1 in range(C):
        for c2 in range(C):
            if(c0 == c1 or c0==c2 or c1==c2):
                continue
            else:
                a = min([a,Dsum[c0][0]+Dsum[c1][1]+Dsum[c2][2]])
print(a)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

for i in range(N):
    tmp = list(map(int,input().split()))
    for j in range(N):
        for k in range(C):
            c[(i+j+2)%3][k] += D[tmp[j]-1][k]

#3色選んで違和感を求める
Iwakan = 1e+10
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
            tmp_Iwakan = 0
            tmp_Iwakan += c[0][i]+c[1][j]+c[2][k]
            Iwakan = min(Iwakan,tmp_Iwakan)

print(Iwakan)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

for i in range(N):
    tmp = list(map(int,input().split()))
    for j in range(N):
        for k in range(C):
            c[(i+j+2)%3][k] += D[tmp[j]-1][k]

#3色選ぶ
choose_C_list = list(itertools.permutations(C_list,3))
Iwakan = 1e+10
for choose_C in choose_C_list:
    tmp_Iwakan = 0
    tmp_Iwakan += c[0][choose_C[0]]+c[1][choose_C[1]]+c[2][choose_C[2]]
    Iwakan = min(Iwakan,tmp_Iwakan)

print(Iwakan)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import sys

N, N1 = tuple([int(x) for x in sys.stdin.readline().split()])
D, C = [], []

for _ in range(N1):
    D.append([int(x) for x in sys.stdin.readline().split()])
for _ in range(N):
    C.append([int(x) for x in sys.stdin.readline().split()])

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

min_cost = 2**64
for colors in itertools.permutations(range(N1)):
    cost = 0
    for j in range(N1):
        cost += color_count[0][j] * D[j][colors[0]]
        cost += color_count[1][j] * D[j][colors[1]]
        cost += color_count[2][j] * D[j][colors[2]]
    if cost < min_cost:
        min_cost = cost
print(min_cost)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

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

#3色選ぶ
choose_C_list = list(itertools.permutations(C_list,3))
Iwakan = 1e+10
for choose_C in choose_C_list:
    tmp_Iwakan = 0
    for i in range(3):
        for cell in c[i]:
            tmp_Iwakan += D[cell-1][choose_C[i]-1]
    Iwakan = min(Iwakan,tmp_Iwakan)

print(Iwakan)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import sys

N, N1 = tuple([int(x) for x in sys.stdin.readline().split()])
D, C = [], []

for _ in range(N1):
    D.append([int(x) for x in sys.stdin.readline().split()])
for _ in range(N):
    C.append([int(x) for x in sys.stdin.readline().split()])

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

min_cost = 2**64
for colors in list(itertools.permutations(range(N1))):
    cost = 0
    for i in range(3):
        for j, c in enumerate(color_count[i]):
            cost += c * D[j][colors[i]]
    if cost < min_cost:
        min_cost = cost
print(min_cost)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from itertools import permutations


def cost(comb):
    cost = 0
    for r in range(N):
        for c in range(N):
            if (r + c) % 3 == 0:
                cost += D[G[r][c] - 1][comb[0] - 1]
            elif (r + c) % 3 == 1:
                cost += D[G[r][c] - 1][comb[1] - 1]
            else:
                cost += D[G[r][c] - 1][comb[2] - 1]

    return cost


N, C = map(int, input().split())
D = [[int(_) for _ in input().split()] for i in range(C)]
G = [[int(_) for _ in input().split()] for i in range(N)]
combs = permutations(range(1, C + 1), 3)
min_cost = min([cost(comb) for comb in combs])
print(min_cost)

Submission status: Time Limit Exceeded

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

ans = float('inf')
for iro1 in range(c):
    for iro2 in range(c):
        if iro1 != iro2:
            for iro3 in range(c):
                if iro1 != iro3 and iro2 != iro3:
                    temp = 0
                    for i in range(n):
                        for j in range(n):
                            if (i+j+2) % 3 == 0:
                                temp += d[grid[i][j]-1][iro1]
                            elif (i+j+2) % 3 == 1:
                                temp += d[grid[i][j]-1][iro2]
                            else:
                                temp += d[grid[i][j]-1][iro3]
                    if ans > temp:
                        ans = temp

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import functools


@functools.lru_cache(maxsize=None)
def paint(i, c):  # i = 0, 1, 2
    cost = 0
    for row in range(N):
        for col in range(N):
            if (row + col) % 3 == i:
                cost += D[G[row][col] - 1][c - 1]

    return cost


def cost(comb):
    cost = 0
    for i in range(3):
        cost += paint(i, comb[i])

    return cost


if __name__ == '__main__':
    from itertools import permutations
    N, C = map(int, input().split())
    D = [[int(_) for _ in input().split()] for i in range(C)]
    G = [[int(_) for _ in input().split()] for i in range(N)]
    combs = permutations(range(1, C + 1), 3)
    min_cost = min([cost(comb) for comb in combs])
    print(min_cost)

Submission status: Time Limit Exceeded

Solution code:
N, C = map(int, input().split())              # 同上。map関数を使うとこのように書ける

D = [[0 for i in range(C)] for j in range(C)]
c = [[0 for i in range(N)] for j in range(N)]
iwakan = [[[0 for i in range(N)] for j in range(N)] for k in range(C)]

for i in range(C):
    D[i] = input().split()

for i in range(C):
    for j in range(C):
        D[i][j] = int(D[i][j])

for i in range(N):
    c[i] = input().split()

for i in range(N):
    for j in range(N):
        c[i][j] = int(c[i][j])


# まず違和感リストを作る。
for i in range(C):
    for j in range(N):
        for k in range(N):
            iwakan[i][j][k] = D[c[j][k] - 1][i]

# 違和感リストから違和感の合計直を求める。
sum_min = 9999999999

for i in range(C):
    for j in range(C):
        for k in range(C):
            if (i == j) or (j == k) or (k == i):
                pass
            else:
                sum_tmp = 0
                for l in range(N):
                    for m in range(N):
                        if(l + m) % 3 == 0:
                            sum_tmp = sum_tmp + iwakan[i][l][m]
                        elif(l + m) % 3 == 1:
                            sum_tmp = sum_tmp + iwakan[j][l][m]
                        else:
                            sum_tmp = sum_tmp + iwakan[k][l][m]
                if sum_min > sum_tmp:
                    sum_min = sum_tmp

print(sum_min)

Submission status: Time Limit Exceeded

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[grid - 1][color - 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: Time Limit Exceeded

Solution code:
import itertools
import sys

N, N1 = tuple([int(x) for x in sys.stdin.readline().split()])
D, C = [], []

for _ in range(N1):
    D.append([int(x) for x in sys.stdin.readline().split()])
for _ in range(N):
    C.append([int(x) for x in sys.stdin.readline().split()])

min_cost = 2**64
for colors in list(itertools.permutations(range(1, N1 + 1))):
    cost = 0
    for i in range(N):
        for j in range(N):
            if C[i][j] != colors[(i + j) % 3]:
                cost += D[C[i][j] - 1][colors[(i + j) % 3] - 1]
    if cost < min_cost:
        min_cost = cost
print(min_cost)

Submission status: Time Limit Exceeded

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 = 1145141919
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: Time Limit Exceeded

Solution code:
N, C = 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())))

ans = 1145141919810
for c0 in range(C):
    for c1 in range(C):
        if c0 == c1: continue
        for c2 in range(C):
            if c1 == c2 or c2 == c0: continue
            color = [c0, c1, c2]
            strange = 0
            for i in range(1, N+1):
                for j in range(1, N+1):
                    strange += D[c[i-1][j-1]-1][color[(i + j) % 3]]
            ans = min(ans, strange)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
def paint(i, c):  # i = 0, 1, 2
    cost = 0
    for row in range(N):
        for col in range(N):
            if (row + col) % 3 == i:
                cost += D[G[row][col] - 1][c - 1]

    return cost


def cost(comb):
    cost = 0
    for i in range(3):
        cost += paint(i, comb[i])

    return cost


if __name__ == '__main__':
    from itertools import permutations
    N, C = map(int, input().split())
    D = [[int(_) for _ in input().split()] for i in range(C)]
    G = [[int(_) for _ in input().split()] for i in range(N)]
    combs = permutations(range(1, C + 1), 3)
    min_cost = min([cost(comb) for comb in combs])
    print(min_cost)

Submission status: Time Limit Exceeded

Solution code:
N, C = map(int,input().split())
D = [0] * C
for i in range(C):
    t = list(map(int,input().split()))
    D[i] = t
c = [0] * N
for i in range(N):
    t = list(map(int,input().split()))
    c[i] = t
Dsum = [0] * C
for k in range(C):
    ccc = [0, 0, 0]
    for i in range(N):
        for j in range(N):
            ccc[(i+j)%3] += D[c[i][j]-1][k]
    Dsum[k] = ccc
ans = 9876543210
for i in range(C):
    for j in range(C):
        for k in range(C):
            if i != j and j != k and k != i:
                ans = min(ans, Dsum[i][0]+Dsum[j][1]+Dsum[k][2])
print(ans)