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: Runtime Error

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: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")
import numpy as np
from collections import Counter
from itertools import permutations


def solve(N: int, C: int, D: "List[List[int]]", c: "List[List[int]]"):
    D = np.array(D)
    onedim = [[], [], []]
    for i in range(N):          # O(N^2)
        for j in range(N):
            onedim[(i+j) % 3].append(c[i][j])
    # print(onedim)
    counters = [Counter(onedim[i]) for i in range(C)]  # O(C*N*N)
    arr = np.empty((C, C))
    for i in range(C):          # O(C*C)
        for j in range(C):
            arr[i][j] = counters[j][i+1]
    # print("arr", arr)
    # print("D", D)
    hint = D.T.dot(arr)         # O(C*C*3)
    # print("D.T@arr\n", hint)
    print(int(min([hint[0][a] + hint[1][b]+hint[2][c]
                   for a, b, c in permutations(range(C), 3)])))
    # O(C*(C-1)*(C-2))
    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: Runtime Error

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

mod3 = {0:[], 1:[], 2:[]}
for i in range(N):
    for j in range(N):
        m = (i+j)%3
        mod3[m].append(color[i][j])
        
from collections import Counter
from itertools import combinations, permutations
cnts = [Counter(mod3[i]) for i in range(3)]
# print(cnts)
ans = float('inf')
for comb in combinations(range(C), 3):
    for p in permutations(comb):
        cond = 0
        for i in range(3):
            for col in cnts[i].keys():
                cond += cnts[i][col]*cost[col][p[i]]
        ans = min(ans, cond)
        #print(cond, p)
print(ans)

Submission status: Runtime Error

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float("INF")

#A
def A():
    return

#B
def B():
    return

#C
def C():
    n = II()
    dp = [inf for i in range(n + 1)]
    ans = [1]
    x = 6
    while x <= n:
        ans.append(x)
        x = x * 6
    x = 9
    while x <= n:
        ans.append(x)
        x = x * 9
    ans.sort()
    for i in ans:
        dp[i] = 1
    for i in range(1, n + 1):
        if not i in ans:
            a = bisect.bisect_left(ans, i)
            for k in range(a):
                #print(i,ans[k], a)
                dp[i] = min(dp[i - ans[k]] + 1, dp[i])
    print(dp[n])

    return

#D
def D():
    n, c = LI()
    D = LIR(c)
    C = LIR_(n)
    CL = list(itertools.permutations(range(c), 3))
    ans = inf
    amari0 = [0 for i in range(30)]
    amari1 = amari0[::1]
    amari2 = amari0[::1]
    for y in range(n):
        for x in range(n):
            amari = (x + y) % 3
            if amari == 0:
                amari0[C[y][x]] += 1
            if amari == 1:
                amari1[C[y][x]] += 1
            if amari == 2:
                amari2[C[y][x]] += 1
    for c0, c1, c2 in CL:
        ansb = 0
        for i in range(C):
            ansb += D[i][c0] * amari0[i]
            ansb += D[i][c1] * amari1[i]
            ansb += D[i][c2] * amari2[i]
        ans = min(ans, anb)

            
    print(ans)

    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Runtime Error

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float("INF")

#A
def A():
    return

#B
def B():
    return

#C
def C():
    n = II()
    dp = [inf for i in range(n + 1)]
    ans = [1]
    x = 6
    while x <= n:
        ans.append(x)
        x = x * 6
    x = 9
    while x <= n:
        ans.append(x)
        x = x * 9
    ans.sort()
    for i in ans:
        dp[i] = 1
    for i in range(1, n + 1):
        if not i in ans:
            a = bisect.bisect_left(ans, i)
            for k in range(a):
                #print(i,ans[k], a)
                dp[i] = min(dp[i - ans[k]] + 1, dp[i])
    print(dp[n])

    return

#D
def D():
    n, c = LI()
    D = LIR(c)
    C = LIR_(n)
    CL = list(itertools.permutations(range(c), 3))
    ans = inf
    amari0 = [0 for i in range(30)]
    amari1 = amari0[::1]
    amari2 = amari0[::1]
    for y in range(n):
        for x in range(n):
            amari = (x + y) % 3
            if amari == 0:
                amari0[D[y][x]] += 1
            if amari == 1:
                amari1[D[y][x]] += 1
            if amari == 2:
                amari2[D[y][x]] += 1
    for c0, c1, c2 in CL:
        ansb = 0
        for i in range(C):
            ansb += D[i][c0] * amari0[i]
            ansb += D[i][c1] * amari1[i]
            ansb += D[i][c2] * amari2[i]
        ans = min(ans, anb)

            
    print(ans)

    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(1000000)

If True:
    if 0==0:
        # Start Input code ---------------------------------------
        N,C=map(int,input().split())
        c=[[0 for j in range(C)] for i in range(3)]
        D=[[0 for i in range(C)] for j in range(C)]
        for i in range(C):
            D[i]=[int(x) for x in input().split()]
        for x in range(N):
            y=0
            for j in input().split():
                c[(x+y)%3][int(j)-1]+=1
                y+=1
        # End Input code ---------------------------------------

St=[[0 for i in range(3)] for j in range(C)]
ans=10**20
for c1 in range(C):
    for c2 in range(C):
        for c3 in range(C):
            cc=0
            dd=0
            for i in range(C):
                cc+=c[0][i]*D[i][c1]
                cc+=c[1][i]*D[i][c2]
                cc+=c[2][i]*D[i][c3]
            if len(set([c1,c2,c3]))==3:
                ans=min(ans,cc)
print(ans)

Submission status: Runtime Error

Solution code:
from itertools import permutations
from collections import deque
from collections import Counter
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)]

r0 = deque()
r1 = deque()
r2 = deque()
for i in range(N):
    for j in range(N):
        rest = (i+1+j+1) % 3
        if rest == 0:
            r0.append(c[i][j]-1)
        elif rest == 1:
            r1.append(c[i][j]-1)
        else:
            r2.append(c[i][j]-1)
c0 = Counter(r0)
c1 = Counter(r1)
c2 = Counter(r2)
ans = 10**10
for p in permutations([i for i in range(C)], 3):
    point = 0
    point += sum([d[k][p[0] * v] for k, v in c0.items()])
    point += sum([d[k][p[1] * v] for k, v in c1.items()])
    point += sum([d[k][p[2] * v] for k, v in c2.items()])
    ans = min(ans, point)
print(ans)

Submission status: Runtime Error

Solution code:
from itertools import permutations

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

table = list(permutations(range(C), 3))
ans = []

for a, b, c in table:
    dep = 0
    for i in range(N):
        for j in range(N):
            num = v[i][j]
            if (i+j)%3 == 0:
                dep += D[num][a]
            elif (i+j)%3 == 1:
                dep += D[num][b]
            else:
                dep += D[num][c]
    ans.append(dep)
print(min(ans))

Submission status: Runtime Error

Solution code:
from itertools import permutations

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]

table = list(permutations(range(C), 3))
ans = []

for a, b, c in table:
    dep = 0
    for i in range(N):
        for j in range(N):
            num = v[i][j]
            if (i+j)%3 == 0:
                dep += D[num][a]
            elif (i+j)%3 == 1:
                dep += D[num][b]
            else:
                dep += D[num][c]
    ans.append(dep)
print(min(ans))

Submission status: Runtime Error

Solution code:
from itertools import permutations
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)]  # 初期盤面
X = [[0] * C for i in range(3)]  # modが0~2 × 各色への変更 の違和感の和

for c in range(C):  # 色
    tmp = [0] * 3  # 各modの違和感の和
    for i in range(N):
        for j in range(N):
            tmp[(i + j) % 3] += D[G[i][j] - 1][c]
    for t in range(3):
        X[c][t] = tmp[t]

ans = float('inf')
for c1, c2, c3 in permutations(range(C), 3):
    ans = min(ans, X[0][c1] + X[1][c2] + X[2][c3])

print(ans)

Submission status: Runtime Error

Solution code:
N, C = map(int, input().split())
 
D = [ [int(i) for i in input().split()] for _ in xrange(C) ]
c = [ [int(i) for i in input().split()] for _ in xrange(N) ]
 
costD = [ [0, 0, 0] for _ in xrange(C)]
 
for c0 in xrange(C):
    for i in xrange(N):
        for j in xrange(N):
            costD[c0][(i+j)%3] += D[c[i][j]-1][c0]
 
kohoD = []
 
for c1 in xrange(C):
    for c2 in xrange(C):
        if c1 == c2:
            continue
        for c3 in xrange(C):
            if c1 == c3 or c2 == c3:
                continue
            kohoD += [(costD[c1][0] + costD[c2][1] + costD[c3][2])]
 
print(min(kohoD))

Submission status: Runtime Error

Solution code:
import itertools
import sys
input = sys.stdin.readline()


def main():
    N, C = map(int, input().split())
    D = [list(map(int, input().split())) for _ in range(C)]
    CC = [list(map(lambda x: int(x) - 1, 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]

    res = float("inf")
    color = [i for i in range(C)]
    for i, c in enumerate(list(itertools.permutations(color, 3))):
        tmp = 0
        for it in range(3):
            tmp += cost[it][c[it]]
        res = min(res, tmp)

    print(res)

main()

Submission status: Runtime Error

Solution code:
import itertools
import sys
input = sys.input.readline()


def main():
    N, C = map(int, input().split())
    D = [list(map(int, input().split())) for _ in range(C)]
    CC = [list(map(lambda x: int(x) - 1, 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]

    res = float("inf")
    color = [i for i in range(C)]
    for i, c in enumerate(list(itertools.permutations(color, 3))):
        tmp = 0
        for it in range(3):
            tmp += cost[it][c[it]]
        res = min(res, tmp)

    print(res)

main()

Submission status: Runtime Error

Solution code:
import sys

s = sys.stdin.readlines()

N,C = map(int,s[0].split())
D = [[int(i) for i in s[j+1].split()] for j in range(C)]
c = [[int(i) for i in s[c+1+j].split()] for j in range(N)]

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

D_sum = [[0]*C for _ in range(3)]
for i in range(C):
    for j in range(C):
        for k in range(3):
            D_sum[k][j] += D[i][j] * c_sum[k][i]

ans = 1000*500*500
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
            else:
                ans = min(ans, D_sum[0][i]+D_sum[1][j]+D_sum[2][k])
print(ans)

Submission status: Runtime Error

Solution code:
import sys
s =sys.stdin.readlines()
N,C = map(int,s[0].split())
D = [[int(i) for i in sys[1+j].split()] for j in range(C)]
c = [[int(i) for i in sys[C+j].split()] for j in range(N)]

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

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

Submission status: Runtime Error

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

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

x=[[0]*3 for i in range(c)]
for i in range(n):
    for j in range(n):
        for k in range(c):
            x[(i+j)%3][k]+=d[init[i][j]-1][k]



ans=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:
                ans=min(ans,x[0][i]+x[1][j]+x[2][k])

print(ans)

Submission status: Runtime Error

Solution code:
N,C=map(int, input().split())
D=[tuple(map(int, input().split())) for _ in range(C)]
c = [[0 for _ in range(3)] for _ in range(C)]
for j in range(N):
    i=0
    for v in map(int, input().split()):
        c[(i+j)%3][v-1] += 1
        i += 1

ans = float("inf")
for i in range(C):
    for j in range(C):
        if i!=j:
            for k in range(C):
                if i!=k and j!=k:
                    tmp = 0
                    for l in range(C):
                        tmp+=D[l][i]*c[0][l]
                    for l in range(C):
                        tmp+=D[l][j]*c[1][l]
                    for l in range(C):
                        tmp+=D[l][k]*c[2][l]
                    if tmp<ans:
                        ans=tmp

print(ans)

Submission status: Runtime Error

Solution code:
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
428
k-mbp:ABC99 kaibe$ cat D.py 
N,C = map(int,input().split())

D = []
c = []

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

c1 = []
c2 = []
c3 = []

from itertools import product

for i,j in product(range(N),repeat=2):
    if (i+j)%3 == 0:
        c1.append(c[i][j])
    elif (i+j)%3 == 1:
        c2.append(c[i][j])
    else:
        c3.append(c[i][j])
val=[]
cnt=[[],[],[]]


for j in range(C):
    cnt[0].append(c1.count(j+1))
    cnt[1].append(c2.count(j+1))
    cnt[2].append(c3.count(j+1))

for i in product(range(C),repeat=3):
    dif = 0
    if i[0]!=i[1] and i[1]!=i[2] and i[2]!=i[0]:
        for j in range(C):
            dif += D[j][i[0]] * cnt[0][j]
            dif += D[j][i[1]] * cnt[1][j]
            dif += D[j][i[2]] * cnt[2][j]
        val.append(dif)

print(min(val))

Submission status: Runtime Error

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

D = []
c = []

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

c1 = []
c2 = []
c3 = []

from itertools import product

for i,j in product(range(N),repeat=2):
    if (i+j)%3 == 0:
        c1.append(c[i][j])
    elif (i+j)%3 == 1:
        c2.append(c[i][j])
    else:
        c3.append(c[i][j])

val=[]

for i in product(set(c1),set(c2),set(c3)):
    dif = 0
    if i[0]!=i[1] and i[1]!=i[2] and i[2]!=i[0]:
        for j,k in product(range(N),repeat=2):
            dif += D[c[j][k]-1][i[(j+k)%3]-1]
        val.append(dif)

print(min(val))

Submission status: Runtime Error

Solution code:
import numpy as np
N, C = map(int, input().split())
D = np.array(map(int, input().split()), dtype=int)
for i in range(C-1):
    D = np.vstack((D, np.array(map(int, input().split()), dtype=int)))
Z = np.array(map(int, input().split()), dtype=int)
for i in range(N-1):
    Z = np.vstack((c, np.array(map(int, input().split()), dtype=int)))
num = np.zeros(size=(3,C), dtype=int)
for i in range(3):
    X = np.array([[(x+y+2)%3==i for y in range(N)] for x in range(N)])
    for c in range(C):
        Y = (Z*X)==c+1
        num[i,c] = Y.sum()
costs = np.matmul(num, D)
mincost = 10**10
for c0 in range(C):
    for c1 in range(C):
        if c1 ==c0:
            continue
        for c2 in range(C):
            if c2 == c1:
                continue
            cost = costs[0,c0]+costs[1,c1]+costs[2,c2]
            mincost = min(mincost, cost)
print(mincost)

Submission status: Runtime Error

Solution code:
import numpy as np
ans=10**9
a=np.array([0,0,0])
b=np.array([0,0,0])
c=np.array([0,0,0])
s=[]
t=[]
N,C=map(int,input().split())
for i in range(C):
    s.append(list(map(int,input().split())))
for i in range(N):
    t.append(list(map(int,input().split())))
for j in range(N):
    for i in range(N):
        if (i+j)%3==0:
            a+=np.array(s[t[i][j]-1])
        elif (i+j)%3==1:
            b+=np.array(s[t[i][j]-1])
        else:
            c+=np.array(s[t[i][j]-1])
from itertools import permutations
for i,j,k in permutations(range(C),3):
    p=a[i]+b[j]+c[k]
    ans=min(p,ans)
print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np
ans=10**9
a=np.array([0,0,0])
b=np.array([0,0,0])
c=np.array([0,0,0])
s=[]
t=[]
N,C=map(int,input().split())
for i in range(C):
    s.append(list(map(int,input().split())))
for i in range(N):
    t.append(list(map(int,input().split())))
for j in range(N):
    for i in range(N):
        if (i+j)%3==0:
            a+=np.array(s[t[i][j]-1])
        elif (i+j)%3==1:
            b+=np.array(s[t[i][j]-1])
        else:
            c+=np.array(s[t[i][j]-1])
from itertools import permutations
for i,j,k in list(permutations([0,1,2])):
    p=a[i]+b[j]+c[k]
    ans=min(ans,p)
print(ans)

Submission status: Runtime Error

Solution code:
N,C=map(int,input().split(' '))
D=[]
for _ in range(C):
  D.append([ x for x in map(int,input().split(' '))])

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

x=float('inf')

memo={}

for seq in [[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]]:
  counter=[[0]*C for _ in range(3)]
  for i in range(N):
    for j in range(N):
      b=i%3
      cur=c[i][j]
      counter[seq[(j+b)%3]][cur-1]+=1
      #s+=D[cur-1][seq[(j+b)%3]]
  if str(counter) in memo:
    s=memo(str(counter))
    if s<x:
      x=s
  else:
    memox=x
    for c0 in range(C):
      for c1 in range(C):
        if c1==c0:
          continue
        for c2 in range(C):
          if c2==c0 or c2==c1:
            continue
          else:
            s=0
            for i, cx in enumerate(counter[0]):
              s+=D[i][c0]*cx
            for i, cx in enumerate(counter[1]):
              s+=D[i][c1]*cx
            for i, cx in enumerate(counter[2]):
              s+=D[i][c2]*cx
          if s<memox:
            memox=s
    memo[str(counter)]=memox
    if memox<x:
      x=memox


print(x)

Submission status: Runtime Error

Solution code:
x=input().split()
n=int(x[0])
c=int(x[1])
dlist=[0]*(c*c)
clist=[0]*(n*n)
cost1=[]
cost2=[]
cost3=[]
x=0
for i in range (c):
    a=input().split()
    for i in a:
        dlist[x]=i
        x=x+1
x=0
for i in range (n):
    a=input().split()
    for i in a:
        clist[x]=i
        x+=1
x=0
list1=[]
list2=[]
list3=[]
y=0
yy=0
while y<n:
    while yy<n:
        if (y+yy)%3==0:
            list1.append(clist[y*n+yy])
        elif (y+yy)%3==1:
            list2.append(clist[y*n+yy])
        elif (y+yy)%3==2:
            list3.append(clist[y*n+yy])
        yy=yy+1
    y=y+1
    yy=0
 
y=1
y2=1
y3=1
mini=99999999999999999999
while y<=c:
    cost=0
    for i in list1:
        if i!=y:
            cost=cost+dlist[(i-1)*c+y-1]
    cost1.append(cost)
    y=y+1
while y2<=c:
    cost=0
    for i in list2:
        if i!=y2:
            cost=cost+dlist[(i-1)*c+y2-1]
    cost2.append(cost)
    y2=y2+1
while y3<=c:
    cost=0
    for i in list3:
        if i!=y3:
            cost=cost+dlist[(i-1)*c+y3-1]
    cost3.append(cost)
    y3=y3+1
x=1
x2=2
x3=3
while x<=c:
    while x2<=c:
        if x2==x:
            x2+=1
        if x2>c:
            break
        while x3<=c:
            if x3==x or x3==x2:
                x3+=1
            if x3==x or x3==x2:
                x3+=1
            if x3>c:
                break
            
            mini=min(mini, cost1[x-1]+cost2[x2-1]+cost3[x3-1])
            x3+=1
        x2+=1
        x3=1
    x+=1
    x2=1
    x3=1
 
print(mini)

Submission status: Runtime Error

Solution code:
x=input().split()
n=int(x[0])
c=int(x[1])
dlist=[0]*(c*c)
clist=[0]*(n*n)
print(dlist)
cost1=[]
cost2=[]
cost3=[]
x=0
for i in range (c):
    a=input().split()
    for i in a:
        dlist[x]=i
        x=x+1
x=0
for i in range (n):
    a=input().split()
    for i in a:
        clist[x]=i
        x+=1
x=0
list1=[]
list2=[]
list3=[]
y=0
yy=0
while y<n:
    while yy<n:
        if (y+yy)%3==0:
            list1.append(clist[y*n+yy])
        elif (y+yy)%3==1:
            list2.append(clist[y*n+yy])
        elif (y+yy)%3==2:
            list3.append(clist[y*n+yy])
        yy=yy+1
    y=y+1
    yy=0
 
y=1
y2=1
y3=1
mini=99999999999999999999
while y<=c:
    cost=0
    for i in list1:
        if i!=y:
            cost=cost+dlist[(i-1)*c+y-1]
    cost1.append(cost)
    y=y+1
while y2<=c:
    cost=0
    for i in list2:
        if i!=y2:
            cost=cost+dlist[(i-1)*c+y2-1]
    cost2.append(cost)
    y2=y2+1
while y3<=c:
    cost=0
    for i in list3:
        if i!=y3:
            cost=cost+dlist[(i-1)*c+y3-1]
    cost3.append(cost)
    y3=y3+1
x=1
x2=2
x3=3
while x<=c:
    while x2<=c:
        if x2==x:
            x2+=1
        if x2>c:
            break
        while x3<=c:
            if x3==x or x3==x2:
                x3+=1
            if x3==x or x3==x2:
                x3+=1
            if x3>c:
                break
            
            mini=min(mini, cost1[x-1]+cost2[x2-1]+cost3[x3-1])
            x3+=1
        x2+=1
        x3=1
    x+=1
    x2=1
    x3=1
 
print(mini)

Submission status: Runtime Error

Solution code:
import itertools

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

diff_by_pos_color_pair = [[0 for _ in range(C)] for _ in range(3)]
for i in range(N):
    for j, color_from in enumerate(map(lambda x: int(x) - 1, input().split())):
        pos = (i + j) % 3
        for color_to in range(C):
            diff_by_pos_color_pair[pos][color_to] += D[color_from][color_to]


min_diff = float("inf")
for ccs in itertools.permutations(range(C), 3):
    diff = 0
    for pos, color in enumerate(ccs):
        diff += diff_by_pos_color_pair[pos][ccs[color]]
    min_diff = min(min_diff, diff)

print(min_diff)

Submission status: Runtime Error

Solution code:
import itertools

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

diff_by_pos_color_pair = [[0 for _ in range(C)] for _ in range(3)]
for i in range(N):
    for j in range(N):
        pos = (i + j) % 3
        for color in range(C):
            diff_by_pos_color_pair[pos][color] += D[c[i][j]][color]


min_diff = float("inf")
for ccs in itertools.permutations(range(C), 3):
    diff = 0
    for pos, color in enumerate(ccs):
        diff += diff_by_pos_color_pair[pos][ccs[color]]
    min_diff = min(min_diff, diff)

print(min_diff)

Submission status: Runtime Error

Solution code:
from pprint import pprint
N, C = [int(i) for i in input().split()]
D_xy = []
for _ in range(C):
    D_xy.append([int(i) for i in input().split()])
c_ij = []
for _ in range(N):
    c_ij.append([int(i) for i in input().split()])

# pprint(D_xy)
# pprint(c_ij)

clusters = [[] for _ in range(3)]
for i in range(N):
    for j in range(N):
         if (i+j) % 3 == 0:
             clusters[0].append(c_ij[i][j])
         elif (i+j) % 3 == 1:
             clusters[1].append(c_ij[i][j])
         elif (i+j) % 3 == 2:
             clusters[2].append(c_ij[i][j])
         else:
             # print(i+j % 3) # % の前は()でくくらないと順番が狂う
             # print("Something wrong")
             pass

# 色が c 通りある場合，色の組み合わせは およそ c**3 通りある訳だけれども．
# 現実的なアプローチとしては，まずそれっぽい解を見つける．
# 他の候補は，計算過程でその最小値を超えたらpassするみたいな感じで進めるのが良いのかな?

cost_matrix = [[0 for i in range(3)] for j in range(C)] # cluster_i to c の距離を予め計算する
for i in range(3):
    for c in range(C):
        cost = 0
        for item in clusters[i]:
            cost += D_xy[item-1][c] # item-1 が index に対応
        cost_matrix[i][c] = cost

# print("cost_matrix")
# pprint(cost_matrix)

## cost_matrixの中から一番賢い組み合わせを選択する
min = float('infinity')
for i in range(C):
    for j in range(C):
        if j == i:
            continue
        for k in range(C):
            if k == i or k == j:
                continue
            score = cost_matrix[0][i] + cost_matrix[1][j] + cost_matrix[2][k]
            # print(i,j,k,"score:",score)
            if score < min:
                min = score
print(min)

Submission status: Runtime Error

Solution code:
import functools  # Python3 
N,M = map(int,input().split())
x, y, z = [0] * N, [0] * N, [0] * N
for i in range(N):
	x[i], y[i], z[i] = map(int,input().split())

if M==0:
	print(0)
	exit()

ppp = functools.reduce(lambda x,y: x+y,sorted([ x[i]+y[i]+z[i] for i in range(N)])[-M:])
pmp = functools.reduce(lambda x,y: x+y,sorted([ x[i]-y[i]+z[i] for i in range(N)])[-M:])
ppm = functools.reduce(lambda x,y: x+y,sorted([ x[i]+y[i]-z[i] for i in range(N)])[-M:])
pmm = functools.reduce(lambda x,y: x+y,sorted([ x[i]-y[i]-z[i] for i in range(N)])[-M:])
mpp = functools.reduce(lambda x,y: x+y,sorted([-x[i]+y[i]+z[i] for i in range(N)])[-M:])
mpm = functools.reduce(lambda x,y: x+y,sorted([-x[i]+y[i]-z[i] for i in range(N)])[-M:])
mmp = functools.reduce(lambda x,y: x+y,sorted([-x[i]-y[i]+z[i] for i in range(N)])[-M:])
mmm = functools.reduce(lambda x,y: x+y,sorted([-x[i]-y[i]-z[i] for i in range(N)])[-M:])

MAX = 0
for lis in [ppp,pmp,ppm,pmm,mpp,mpm,mmp,mmm]:
	if lis  > MAX:
		MAX = lis
print(MAX)

Submission status: Runtime Error

Solution code:
N,C=map(int,input().split())
D=[]
for i in range(C):
    Dlist=list(map(int,input().split()))
    D.append(Dlist)
c=[[0]*N*N for i in range(3)]
x=[]
X=[]
for i in range(N):
    x=list(map(int,input().split()))
    X.append(x)
for i in range(N):
    for j in range(N):
        x=X[i][j]
        c[(i+j)%3][x-1]+=1
def func(res):
    for i in range(C):
        for j in range(C):
            if i!=j:
                for k in range(C):
                    if i!=k and j!=k:
                        total=0
                        for l in range(C):                           
                            total+=D[l][i]*c[0][l]
                            total+=D[l][j]*c[1][l]
                            total+=D[l][k]*c[2][l]
                        if total<res:
                            res=total
    return res
y=10**6
res=func(y)
print(res)