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:
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [input() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [int(input()) for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def roundUp(a, b):
        return -(-a // b)

    @staticmethod
    def toUpperMultiple(a, x):
        return Math.roundUp(a, x) * x

    @staticmethod
    def toLowerMultiple(a, x):
        return (a // x) * x

    @staticmethod
    def nearPow2(n):
        if n <= 0:
            return 0
        if n & (n - 1) == 0:
            return n
        ret = 1
        while(n > 0):
            ret <<= 1
            n >>= 1
        return ret

    @staticmethod
    def sign(n):
        if n == 0:
            return 0
        if n < 0:
            return -1
        return 1

    @staticmethod
    def isPrime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True


class PriorityQueue:
    def __init__(self, l=[]):
        self.__q = l
        heapq.heapify(self.__q)
        return

    def push(self, n):
        heapq.heappush(self.__q, n)
        return

    def pop(self):
        return heapq.heappop(self.__q)


sys.setrecursionlimit(1000000)
MOD = int(1e09) + 7
INF = int(1e30)


def main():
    # sys.stdin = open("Sample.txt")
    N, C = Scanner.map_int()
    D = Scanner.int_list_list(C)
    colors = Scanner.int_list_list(N)
    for i in range(N):
        for j in range(N):
            colors[i][j] -= 1
    ans = INF
    for i in range(6):
        tmp = [[0 for _ in range(N)] for _ in range(N)]
        for h in range(N):
            for w in range(N):
                if (h + w) % 3 == i // 2:
                    tmp[h][w] = 0
                elif (h + w) % 3 == (i // 2 + (i % 2+1)) % 3:
                    tmp[h][w] = 1
                else:
                    tmp[h][w] = 2
        for a in range(C):
            for b in range(C):
                if a == b:
                    continue
                for c in range(C):
                    if a == c or b == c:
                        continue
                    now = 0
                    for h in range(N):
                        for w in range(N):
                            if tmp[h][w] == 0:
                                now += D[colors[h][w]][a]
                            elif tmp[h][w] == 1:
                                now += D[colors[h][w]][b]
                            else:
                                now += D[colors[h][w]][c]
                    ans = min(ans, now)
    print(ans)
    return


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
#coding: utf-8
import math
import heapq
import bisect
import numpy as np
from collections import Counter
#from scipy.misc import comb

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

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

Grid = []
for i in range(N):
    c = list(map(int, input().split()))
    g = list(map(lambda x: x-1, c))
    Grid.append(g)

ans = 1000*N*N
for i in range(C):
    for j in range(C):
        for k in range(C):
            if (i-j)*(j-k)*(k-i) == 0:
                continue
            tmp = 0
            for a in range(N):
                for b in range(N):
                    if (a+b)%3 == 0:
                        tmp += D[Grid[a][b]][i]
                    elif (a+b)%3 == 1:
                        tmp += D[Grid[a][b]][j]
                    else:
                        tmp += D[Grid[a][b]][k]
            ans = min(ans,tmp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
n,c = map(int,input().split())
cost = [list(map(int,input().split())) for i in range(c)]
grid = [list(map(int,input().split())) for i in range(n)]
sum0 = []
sum1 = []
sum2 = []
for color in range(c):
  s0,s1,s2 = 0,0,0
  for i in range(n):
    for j in range(n):
      x = grid[i][j]-1
      if (i+j)%3 == 0:
        s0 += cost[x][color]
      elif (i+j)%3 == 1:
        s1 += cost[x][color]
      else:
        s2 += cost[x][color]
  sum0.append((s0,color))
  sum1.append((s1,color))
  sum2.append((s2,color))
ans = 10**18
for a,b,c in product(sum0,sum1,sum2):
  if a[1] != b[1] and b[1] != c[1] and c[1] != a[1]:
    ans = min(ans,a[0]+b[0]+c[0])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import os
import sys

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353


# 色のパターン 30*29*28 == 24360
# 全部試すだけ

N, C = list(map(int, sys.stdin.buffer.readline().split()))
D = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(C)]
S = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]

D = np.array(D, dtype=int)
S = np.array(S, dtype=int) - 1

md = np.zeros((N, N), dtype=int)
md += np.arange(N, dtype=int)
md += np.arange(N, dtype=int)[:, None]
md %= 3

ans = INF
for colors in itertools.permutations(range(C), r=3):
    # S[md == 0] -> colors[0]
    s = 0
    s += D[S[md == 0], colors[0]].sum()
    s += D[S[md == 1], colors[1]].sum()
    s += D[S[md == 2], colors[2]].sum()
    ans = min(ans, s)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools


def main():
    N, C = map(int, input().split())

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

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

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

    for i in range(1, N + 1):
        for j in range(1, N + 1):
            clazz[(i + j) % 3].append(CNN[i - 1][j - 1])

    ans = 99999999999999999999
    for colors_cmb in itertools.combinations(range(1, C + 1), 3):
        for colors in itertools.permutations(colors_cmb):

            color1, color2, color3 = colors

            ans_temp = 0
            ans_temp += len(list(filter(lambda c: c == 1,
                                        clazz[0]))) * DCC[0][color1 - 1]
            ans_temp += len(list(filter(lambda c: c == 2,
                                        clazz[0]))) * DCC[1][color1 - 1]
            ans_temp += len(list(filter(lambda c: c == 3,
                                        clazz[0]))) * DCC[2][color1 - 1]
            ans_temp += len(list(filter(lambda c: c == 1,
                                        clazz[1]))) * DCC[0][color2 - 1]
            ans_temp += len(list(filter(lambda c: c == 2,
                                        clazz[1]))) * DCC[1][color2 - 1]
            ans_temp += len(list(filter(lambda c: c == 3,
                                        clazz[1]))) * DCC[2][color2 - 1]
            ans_temp += len(list(filter(lambda c: c == 1,
                                        clazz[2]))) * DCC[0][color3 - 1]
            ans_temp += len(list(filter(lambda c: c == 2,
                                        clazz[2]))) * DCC[1][color3 - 1]
            ans_temp += len(list(filter(lambda c: c == 3,
                                        clazz[2]))) * DCC[2][color3 - 1]

            ans = min(ans, ans_temp)

    print(ans)


main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    def fcalc(cl,c):
        f = 0
        for i in range(len(cl)):
            if cl[i] != c:
                f += d[cl[i]-1][c-1]
        return f
                
    n,c = map(int,input().split())
    d = [list(map(int,input().split())) for _ in range(c)]
    color = [list(map(int,input().split())) for _ in range(n)]
    clist = [[],[],[]]
    for i in range(n):
        for j in range(n):
            clist[(i+j+2)%3].append(color[i][j])
    ans_list = []
    for i in range(1,c+1):
        f1 = fcalc(clist[0],i)
        for j in range(1,c+1):
            if i != j:
                f2 = fcalc(clist[1],j)
                for k in range(1,c+1):
                    if j != k and k != i:
                        f3 = fcalc(clist[2],k)
                        ans_list.append(f1+f2+f3)
    print(min(ans_list))
    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    def fcalc(cl,c):
        f = 0
        for i in range(len(cl)):
            if cl[i] != c:
                f += d[cl[i]-1][c-1]
        return f
                
    n,c = map(int,input().split())
    d = [list(map(int,input().split())) for _ in range(c)]
    color = [list(map(int,input().split())) for _ in range(n)]
    clist = [[],[],[]]
    for i in range(n):
        for j in range(n):
            clist[(i+j+2)%3].append(color[i][j])
    ans_list = []
    for i in range(1,c+1):
        for j in range(1,c+1):
            for k in range(1,c+1):
                if not (i==j or j == k or k == i):
                    f1 = fcalc(clist[0],i)
                    f2 = fcalc(clist[1],j)
                    f3 = fcalc(clist[2],k)
                    ans_list.append(f1+f2+f3)
    print(min(ans_list))
    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from itertools import permutations
n, c = [int(i) for i in sys.stdin.readline().split()]
D = dict()
C = dict()
MOD_dict = dict()
INF = 10 ** 18
for i in range(c):
    inp = [int(i) for i in sys.stdin.readline().split()]
    D[i] = inp
for i in range(n):
    inp = [int(i) - 1 for i in sys.stdin.readline().split()]
    C[i] = inp
    MOD_dict[i] = []
    for j in range(n):
        MOD_dict[i].append((i + j) % 3)
best = INF
for perm in permutations(range(c), 3):
    cost = 0
    for i in range(n):
        for j in range(n):
            pre = C[i][j]
            post = perm[MOD_dict[i][j]]
            cost += D[pre][post]
    best = min(cost, best)
print(best)

Submission status: Time Limit Exceeded

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

a=10**9
for c0 in range(C):
  for c1 in range(c0+1,C):
    for c2 in range(c1+1,C):
      s1,s2,s3=0,0,0
      for i in range(N):
        for j in range(N):
          m = (i+j+2)%3
          if m==0:
            s1 += D[c[i][j]][c0]
            s2 += D[c[i][j]][c1]
            s3 += D[c[i][j]][c2]
          elif m==1:
            s1 += D[c[i][j]][c1]
            s2 += D[c[i][j]][c2]
            s3 += D[c[i][j]][c0]
          else:
            s1 += D[c[i][j]][c2]
            s2 += D[c[i][j]][c0]
            s3 += D[c[i][j]][c1]
      a=min(a,s1,s2,s3)
print(a)

Submission status: Time Limit Exceeded

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

def solve(N: int, C: int, D: "List[List[int]]", c: "List[List[int]]"):
    c_list = list(itertools.permutations(range(C),3))
    answer = 10**9
    for zero,one,two in c_list:
        a = 0
        for i in range(N):
            for j  in range(N):
                color = c[i][j]
                if (i+j) % 3 == 0:
                    a+= D[color-1][zero]
                elif (i+j) % 3 == 1:
                    a+= D[color-1][one]
                elif (i+j) % 3 == 2:
                    a+= D[color-1][two]
        answer = min(answer,a)

    print(answer)
    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:
n,c = map(int,input().split())
ds = []
grids = []
for i in range(c):
  ds.append(list(map(int,input().split())))

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

def get_cost(color,grids,ds):
  cost = [0,0,0]
  for l in range(n):
    for m in range(n):
      cost[(l+m)%3] += ds[grids[l][m]-1][color[(l+m)%3]]
  return cost

costa = []
costb = []
costc = []
for i in range(c):
  cost = get_cost([i,i,i],grids,ds)
  costa.append((cost[0],i))
  costb.append((cost[1],i))
  costc.append((cost[2],i))
costa.sort()
costb.sort()
costc.sort()
colors = []
for i in range(3):
  colors.append(costa[i][1])
  colors.append(costb[i][1])
  colors.append(costc[i][1])
costs = []
for i in set(colors):
  for j in set(colors):
    if i==j:
      continue
    for k in set(colors):
      if i==k or j ==k:
        continue
      cost = sum(get_cost([i,j,k],grids,ds))
      costs.append(cost)
print(min(costs))

Submission status: Time Limit Exceeded

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

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

def strange(cb,ca,ds):
  return ds[cb,ca]

costs = []
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
      cost = 0
      color = [i,j,k]
      for l in range(n):
        for m in range(n):
          cost += ds[grids[l][m]-1][color[(l+m)%3]-1]
      costs.append(cost)
print(min(costs))

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())))
col=[]
for i in range(n):
  col.append(list(map(int,input().split())))
lc1=[]
lc2=[]
lc3=[]
for i in range(c):
  ccount1=0
  ccount2=0
  ccount3=0
  for j in range(n):
    for k in range(n):
      if (j+k)%3==0:
        ccount1+=d[col[j][k]-1][i]
      elif (j+k)%3==1:
        ccount2+=d[col[j][k]-1][i]
      else:
        ccount3+=d[col[j][k]-1][i]
  lc1.append(ccount1)
  lc2.append(ccount2)
  lc3.append(ccount3)
min=10**10
for i in range(c):
  for j in range(c):
    for k in range(c):
      if i==j or j==k or i==k:
        pass
      else:
        if min>lc1[i]+lc2[j]+lc3[k]:
          min=lc1[i]+lc2[j]+lc3[k]
print(min)

Submission status: Time Limit Exceeded

Solution code:
# D - Good Grid

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

group0, group1, group2 = [], [], []
for row in range(N):
    for col in range(N):
        if (row + col) % 3 == 0:
            group0.append(c[row][col] -1)
        elif (row + col) % 3 == 1:
            group1.append(c[row][col] -1)
        else:
            group2.append(c[row][col] -1)

ans = []
for color0 in range(C):
    for color1 in range(C):
        for color2 in range(C):
            if len(set([color0, color1, color2])) == 3:
                tmp = 0
                for x in group0:
                    tmp += D[x][color0]
                for x in group1:
                    tmp += D[x][color1]
                for x in group2:
                    tmp += D[x][color2]
                ans.append(tmp)

print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
# D - Good Grid

import numpy as np

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

group0, group1, group2 = [], [], []
for row in range(N):
    for col in range(N):
        if (row + col) % 3 == 0:
            group0.append(c[row][col])
        elif (row + col) % 3 == 1:
            group1.append(c[row][col])
        else:
            group2.append(c[row][col])

ans = []
for color0 in range(C):
    for color1 in range(C):
        for color2 in range(C):
            if len(set([color0, color1, color2])) == 3:
                tmp = 0
                for x in group0:
                    tmp += D[x][color0]
                for x in group1:
                    tmp += D[x][color1]
                for x in group2:
                    tmp += D[x][color2]
                ans.append(tmp)

print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations 
n,m=map(int,input().split())
cost=[]
for i in range(m):
    cost.append([int(i) for i in input().split()])
clr=[]
for i in range(n):
    clr.append([int(i) for i in input().split()])
l=[i for i in range(m)]
ind=[[] for i in range(4)]
for i in range(n):
    for j in range(n):
        curr=(i+1+j+1)%3 
        ind[curr].append(clr[i][j]-1)
mini=10**9 
for i in range(m):
    for j in range(m):
        for k in range(m):
            if i==j or i==k or j==k:
                continue 
            curr=0 
            for x in ind[0]:
                curr+=cost[x][i]
            for x in ind[1]:
                curr+=cost[x][j]
            for x in ind[2]:
                curr+=cost[x][k]
            mini=min(mini,curr)
print(mini)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations 
n,m=map(int,input().split())
cost=[]
for i in range(m):
    cost.append([int(i) for i in input().split()])
clr=[]
for i in range(n):
    clr.append([int(i) for i in input().split()])
l=[i for i in range(m)]
ind=[[] for i in range(4)]
for i in range(n):
    for j in range(n):
        curr=(i+1+j+1)%3 
        ind[curr].append(clr[i][j]-1)
mini=10**9 
for i in permutations(l,3): 
    curr=0 
    for j in range(3):
        for x in ind[j]: 
            curr+=cost[x][i[j]]
    mini=min(mini,curr)
print(mini)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations 
n,m=map(int,input().split())
cost=[]
for i in range(m):
    cost.append([int(i) for i in input().split()])
clr=[]
for i in range(n):
    clr.append([int(i) for i in input().split()])
l=[i for i in range(m)]
ind=[[] for i in range(210)]
for i in range(n):
    for j in range(n):
        curr=(i+1+j+1)%3 
        ind[curr].append(clr[i][j]-1)
mini=10**9 
for i in permutations(l,3): 
    curr=0 
    for j in range(3):
        for x in ind[j]: 
            curr+=cost[x][i[j]]
    mini=min(mini,curr)
print(mini)

Submission status: Time Limit Exceeded

Solution code:
import sys
from itertools import permutations

N,C = map(int,input().split())
D = [list(map(int,sys.stdin.readline().split())) for _ in range(C)]
grids = [list(map(int,sys.stdin.readline().split())) for _ in range(N)]

ans = float('inf')
for cmb in permutations([i for i in range(1,C+1)],3):
  tmp_ans = 0
  for j, row in enumerate(grids):
    for i, val in enumerate(row):
      if val != cmb[(i+j+2)%3]: tmp_ans += D[val-1][cmb[(i+j+2)%3]-1]
      #print(i, j, val, cmb, tmp_ans)
  ans = min(tmp_ans, ans)
  #print(ans, tmp_ans, cmb)
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)]
grids = [list(map(int,input().split())) for _ in range(N)]

ans = float('inf')
for cmb in permutations([i for i in range(1,C+1)],3):
  tmp_ans = 0
  for j, row in enumerate(grids):
    for i, val in enumerate(row):
      if val != cmb[(i+j+2)%3]: tmp_ans += D[val-1][cmb[(i+j+2)%3]-1]
      #print(i, j, val, cmb, tmp_ans)
  ans = min(tmp_ans, ans)
  #print(ans, tmp_ans, cmb)
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)]
Grid = [list(map(int,input().split())) for _ in range(N)]

SumCost = [[0 for _ in range(C)] for _ in range(3)]
for c in range(1,C+1):
  for i in range(N):
    for j in range(N):
      g = ((i+1)+(j+1))%3
      SumCost[g][c-1] += D[Grid[i][j]-1][c-1]

ans = 10**18
for c1 in range(1,C+1):
  for c2 in range(1,C+1):
    for c3 in range(1,C+1):
      if c1 == c2 or c2 == c3 or c3 == c1:
        continue
      ans = min(ans,SumCost[0][c1-1]+SumCost[1][c2-1]+SumCost[2][c3-1])
print(ans)

Submission status: Time Limit Exceeded

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

c = []
for i in range(N):
    tmp = [int(x)-1 for x in input().split()]
    c.append(tmp)

x = [[], [], []] # 0,1,2
for cc in range(C):
    tx = [0] * 3
    for i in range(N):
        for j in range(N):
            tx[(i+j)%3] += d[c[i][j]][cc]
    for i in range(3):
        x[i].append(tx[i])

ans = 10 ** 9
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
            tmp = x[0][i] + x[1][j] + x[2][k]
            if tmp < ans:
                ans = tmp
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations as 敬語使うべきじゃん
N, C = map(int, input().split())
D = [[0] * (C + 1)] + [[0] + list(map(int, input().split())) for _ in range(C)]
c = [[0] * (N + 1)] + [[0] + list(map(int, input().split())) for _ in range(N)]
#print(D, c)

group = [[] for _ in range(3)]
for i in range(1, N + 1):
  for j in range(1, N + 1):
    m = (i + j) % 3
    group[m].append(c[i][j])
#print(group)

#色変えるだで
#色変えたときにかかるコストを先に計算しますよーしますしますし
costs = [[0] * (C + 1) for _ in range(3)]
for i in range(3):
  for color in range(1, C + 1):
    temp = 0
    for j in range(len(group[i])):
      temp += D[group[i][j]][color]
    costs[i][color] = temp
#print(costs)
res = 10 ** 10
for per in list(敬語使うべきじゃん(list(range(1, C + 1)), 3)):
  #print(per)
  #色はグループごとにちがう
  i, j, k = per[0], per[1], per[2]
  res = min(res, costs[0][i] + costs[1][j] + costs[2][k])
print(res)

Submission status: Time Limit Exceeded

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

mod = [[], [], []]

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

ans = float("inf")
for c_i in range(C):
    for c_j in range(C):
        if c_j == c_i:
            continue
        for c_k in range(C):
            if c_k == c_i or c_k == c_j:
                continue
            li = [c_i, c_j, c_k]
            sm = 0
            for i in range(3):
                for clr in mod[i]:
                    sm += d[clr-1][li[i]]

            ans = min(ans, sm)

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

ans = float("inf")
for c_i in range(C):
    for c_j in range(C):
        if c_i == c_j:
            continue
        for c_k in range(C):
            if c_i == c_k or c_j == c_k:
                continue
            sm = 0
            for i in range(N):
                for j in range(N):
                    mod = (i + j + 2) % 3
                    clr = c[i][j]
                    if mod == 2:
                        sm += d[clr-1][c_i]
                    elif mod == 0:
                        sm += d[clr-1][c_j]
                    else:
                        sm += d[clr-1][c_k]
            ans = min(ans, sm)

print(ans)

Submission status: Time Limit Exceeded

Solution code:

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

D = []

for i in range(C):

    d = list(map(int,input().split()))

    D.append(d)

c = []

for i in range(N):

    cc = list(map(int,input().split()))
    c.append(cc)


lis1 = []
lis2 = []
lis3 = []

for c1 in range(C):

    c1 += 1

    now = 0

    for i in range(N):

        for j in range(N):

            if (i + j) % 3 == 0 and c[i][j] != c1:

                now += D[c[i][j]-1][c1-1]

    lis1.append(now)


for c2 in range(C):

    c2 += 1

    now = 0

    for i in range(N):

        for j in range(N):

            if (i + j) % 3 == 1 and c[i][j] != c2:

                now += D[c[i][j]-1][c2-1]

    lis2.append(now)


for c3 in range(C):

    c3 += 1

    now = 0

    for i in range(N):

        for j in range(N):

            if (i + j) % 3 == 2 and c[i][j] != c3:

                now += D[c[i][j]-1][c3-1]

    lis3.append(now)


ans = float("inf")

for i in range(C):

    for j in range(C):

        for k in range(C):


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

            ans = min(ans,lis1[i] + lis2[j] + lis3[k])

print (ans)

Submission status: Time Limit Exceeded

Solution code:

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

D = []

for i in range(C):

    d = list(map(int,input().split()))

    D.append(d)

c = []

for i in range(N):

    cc = list(map(int,input().split()))
    c.append(cc)


ans = float("inf")


for c1 in range(C):

    c1 += 1

    for c2 in range(C):

        c2 += 1

        for c3 in range(C):

            c3 += 1

            


            if c1 == c2 or c2 == c3 or c3 == c1:
                continue;

            now = 0

            for i in range(N):

                for j in range(N):


                    if (i + j) % 3 == 0 and c[i][j] != c1:

                        now += D[c[i][j]-1][c1-1]

                    elif (i + j) % 3 == 1 and c[i][j] != c2:

                        now += D[c[i][j]-1][c2-1]

                    elif (i + j) % 3 == 2 and c[i][j] != c3:

                        now += D[c[i][j]-1][c3-1]

            ans = min(ans,now)


print (ans)

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())))
x=[]
y=[]
z=[]
for d in range(C):
  x.append(0)
  y.append(0)
  z.append(0)
for d in range(C):
  for i in range(N):
    for j in range(N):
      if (i+j)%3==0:
        x[d]+=D[c[i][j]-1][d]
      if (i+j)%3==1:
        y[d]+=D[c[i][j]-1][d]
      if (i+j)%3==2:
        z[d]+=D[c[i][j]-1][d]

num=0
ans=10000000000000
for i in range(C):
  for j in range(C):
    for k in range(C):
      if i!=j and i!=k and j!=k:
        num=x[i]+y[j]+z[k]
        if num<ans:
          ans=num
print(ans)

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())))
x=[]
y=[]
z=[]
for d in range(C):
  x.append(0)
  y.append(0)
  z.append(0)
for d in range(C):
  for i in range(N):
    for j in range((3-i%3)%3,N,3):
      x[d]+=D[c[i][j]-1][d]
    for j in range((1-i%3)%3,N,3):
      y[d]+=D[c[i][j]-1][d]
    for j in range((2-i%3)%3,N,3):
      z[d]+=D[c[i][j]-1][d]
num=0
ans=10000000000000
for i in range(C):
  for j in range(C):
    for k in range(C):
      if i!=j and i!=k and j!=k:
        num=x[i]+y[j]+z[k]
        if num<ans:
          ans=num
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
n,c=map(int,input().split())
lc=[list(map(int,input().split())) for _ in range(c)]
l=[list(map(int,input().split())) for _ in range(n)]
lst=[[],[],[]]
for i in range(n):
    for j in range(n):
        lst[(i+j)%3].append(l[i][j]-1)
com=list(itertools.permutations(list(range(c)),3))
ans=float("inf")
for i in com:
    tmp=0
    for j in range(3):
        for k in lst[j]:
            tmp+=lc[k][i[j]]
    ans=min(ans,tmp)
print(ans)

Submission status: Time Limit Exceeded

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

state = [[0 for _ in range(C)] for _ in range(3)]
for c in range(C):
    for w in range(N):
        for h in range(N):
            cost = D[grid[h][w]-1][c]
            state[(h+w)%3][c] += cost

for c1 in range(C):
    for c2 in range(C):
        if c1 == c2:
            continue
        for c3 in range(C):
            if c3 == c1 or c3 == c2:
                continue
            cost = state[0][c1] + state[1][c2] + state[2][c3]
            if c1 == 0 and c2 == 1 and c3 == 2:
                ans = cost
                continue
            ans = min(cost, ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,C=map(int,input().split())
d=[]
c=[]
for i in range(C):
    d.append([int(j) for j in input().split()])
for i in range(n):
    c.append([int(j) for j in input().split()])
l1=[0 for i in range(C+1)]
l2=[0 for i in range(C+1)]
l3=[0 for i in range(C+1)]

for i in range(n):
    for j in  range(n):
        if (i+j+2)%3==0:
            for k in range(1,C+1):
                l1[k]+=d[c[i][j]-1][k-1]
        if (i+j+2)%3==1:
            for k in range(1,C+1):
                l2[k]+=d[c[i][j]-1][k-1]
        if (i+j+2)%3==2:
            for k in range(1,C+1):
                l3[k]+=d[c[i][j]-1][k-1]
ans=10**100
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 i!=k and j!=k:
                ans=min(ans,l1[i]+l2[j]+l3[k])
print(ans)