Problem:


Score : 400 points

Problem Statement

There is a grid with N rows and N columns of squares. Let (i,j) be the square at the i-th row from the top and the j-th column from the left.

These squares have to be painted in one of the C colors from Color 1 to Color C. Initially, (i,j) is painted in Color c_{i,j}.

We say the grid is a good grid when the following condition is met for all i,j,x,y satisfying 1 \leq i,j,x,y \leq N:

If (i+j) \% 3=(x+y) \% 3, the color of (i,j) and the color of (x,y) are the same.

If (i+j) \%  3 \neq (x+y) \% 3, the color of (i,j) and the color of (x,y) are different.

Here, X \% Y represents X modulo Y.

We will repaint zero or more squares so that the grid will be a good grid.

For a square, the wrongness when the color of the square is X before repainting and Y after repainting, is D_{X,Y}.

Find the minimum possible sum of the wrongness of all the squares.

Constraints

1 \leq N \leq 500

3 \leq C \leq 30

1 \leq D_{i,j} \leq 1000 (i \neq j),D_{i,j}=0 (i=j)

1 \leq c_{i,j} \leq C

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N C
D_{1,1} ... D_{1,C}
:
D_{C,1} ... D_{C,C}
c_{1,1} ... c_{1,N}
:
c_{N,1} ... c_{N,N}

Output

If the minimum possible sum of the wrongness of all the squares is x, print x.

Sample Input 1

2 3
0 1 1
1 0 1
1 4 0
1 2
3 3

Sample Output 1

3

Repaint (1,1) to Color 2. The wrongness of (1,1) becomes D_{1,2}=1.

Repaint (1,2) to Color 3. The wrongness of (1,2) becomes D_{2,3}=1.

Repaint (2,2) to Color 1. The wrongness of (2,2) becomes D_{3,1}=1.

In this case, the sum of the wrongness of all the squares is 3.

Note that D_{i,j} \neq D_{j,i} is possible.

Sample Input 2

4 3
0 12 71
81 0 53
14 92 0
1 1 2 1
2 1 1 2
2 2 1 3
1 1 2 2

Sample Output 2

428



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


Sample output:
3

Submission status: Wrong Answer

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

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

stdin = sys.stdin

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

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

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

ans = inf
for i, j, k in itertools.permutations(range(3), 3):
    tmp = 0
    for num in z:
        tmp += D[num][i]
    for num in o:
        tmp += D[num][j]
    for num in t:
        tmp += D[num][k]
    ans = min(tmp, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from itertools import permutations

n, c = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
cmat = [list(map(int, input().split())) for _ in range(n)]

dcnt = [defaultdict(int) for _ in range(3)]
for i, ci in enumerate(cmat, 1):
    for j, cij in enumerate(ci, 1):
        mod = (i + j) % 3
        dcnt[mod][cij - 1] += 1

ans = 1000 * n
for color in permutations(range(c), 3):
    tmp = 0
    for i, cnt in enumerate(dcnt):
        tmp += sum(d[k][color[i]] * cnt[k] for k in cnt)
    ans = min(ans, tmp)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from itertools import permutations

n, c = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
cmat = [list(map(int, input().split())) for _ in range(n)]

dcnt = [defaultdict(int) for _ in range(3)]
for i, ci in enumerate(cmat, 1):
    for j, cij in enumerate(ci, 1):
        mod = (i + j) % 3
        dcnt[mod][cij - 1] += 1

ans = 1000 * n
for color in permutations(range(c), 3):
    if len(set(color)) == 3:
        tmp = 0
        for i, cnt in enumerate(dcnt):
            tmp += sum(d[k][color[i]] * cnt[k] for k in cnt)
        ans = min(ans, tmp)
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    from sys import stdin
    def input():
        return stdin.readline().strip()
    
    n, c = map(int, input().split())
    d = [list(map(int, input().split())) for _ in range(c)]

    '''
    # if I can change the color of the same square many times
    # Warshall-Floyd algorithm
    for k in range(c):
        for i in range(c):
            for j in range(c):
                if d[i][j] > d[i] + d[j]:
                    d[i][j] = d[i][j]
    '''

    color = [list(map(int, input().split())) for _ in range(n)]

    counters = [[0] * c for _ in range(3)]
    for i in range(n):
        for j in range(n):
            counters[(i+j) % 3][color[i][j] - 1] += 1
    
    # full search
    cost = []
    for group in counters:
        l = []
        for i in range(c):
            num = 0
            for j in range(c):
                num += d[j][i] * group[j]
            l.append((num, i))
        l.sort()
        cost.append(l[c-3:])

    ans = 10 ** 9
    for i in range(3):
        for j in range(3):
            for k in range(3):
                if cost[0][i][1] != cost[1][j][1] and cost[1][j][1] != cost[2][k][1] and cost[2][k][1] != cost[0][i][1]:
                    if ans > cost[0][i][0] + cost[1][j][0] + cost[2][k][0]:
                        ans = cost[0][i][0] + cost[1][j][0] + cost[2][k][0]
    
    print(ans)

main()

Submission status: Wrong Answer

Solution code:
import numpy as np
import itertools
import sys
sys.setrecursionlimit(10**9)



def solve(N,C,D,colormap,new_colors):
    INF=1<<18
    ans = INF
    for j in range(len(new_colors)):
        colors = new_colors[j]
        res = 0
        for mod in range(len(colormap)):
            current_colors = colormap[mod]
            for i in range(len(current_colors)):
                current = current_colors[i]
                if current == 0: break
                new_color = colors[mod]
                res += D[current-1][new_color-1]

        ans = min(res,ans)

    
    return ans

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


    colormap = np.zeros((3,N*N+10),dtype=int)
    mx = 0
    ki = {x:0 for x in range(3)}
    for i in range(1,N+1):
        for j in range(1,N+1):
            k = i+j
            k %= 3
            colormap[k][ki[k]] = c[i-1][j-1]
            ki[k] += 1
           
    
    # print(colormap)
    new_colors = np.array(list(itertools.permutations(list(range(1,C+1)),3)))
    ans = solve(N, C, np.array(D), colormap, new_colors)
    print(ans)


def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')

    # basic types: https://numba.pydata.org/numba-doc/0.13/types.html
    cc.export('solve', '(i8,i8,i8[:,:],i8[:,:],i8[:,:],)')(solve)
    cc.compile()

if __name__ == '__main__':
    # cc_export()
    try:
        from my_module import solve
    except:
        cc_export()
        exit()

    main()

Submission status: Wrong Answer

Solution code:
import numpy as np
import itertools
import sys
sys.setrecursionlimit(10**9)



def solve(N,C,D,colormap,iterate):
    INF=1<<18
    ans = INF
    for j in range(len(iterate)):
        colors = iterate[j]
        res = 0
        for mod in range(len(colormap)):
            current_colors = colormap[mod]
            for i in range(len(current_colors)):
                current = current_colors[i]
                if current == 0: continue
                color = colors[mod]
                res += D[current-1][color-1]

        ans = min(res,ans)

    
    return ans

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


    colormap = np.zeros((3,N*N+10),dtype=int)
    mx = 0
    ki = {x:0 for x in range(3)}
    for i in range(1,N+1):
        for j in range(1,N+1):
            k = i+j
            k %= 3
            colormap[k][ki[k]] = c[i-1][j-1]
            ki[k] += 1
           
    
    # print(colormap)
    ans = solve(N, C, np.array(D), colormap,np.array(list(itertools.permutations(list(range(1,C+1)),3))))
    print(ans)


def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')

    # basic types: https://numba.pydata.org/numba-doc/0.13/types.html
    cc.export('solve', '(i8,i8,i8[:,:],i8[:,:],i8[:,:],)')(solve)
    cc.compile()

if __name__ == '__main__':
    # cc_export()
    try:
        from my_module import solve
    except:
        cc_export()
        exit()

    main()

Submission status: Wrong Answer

Solution code:
import itertools

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

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

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

ans=float('inf')


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


print(ans)

Submission status: Wrong Answer

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

from itertools import product

N, C = list(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)]

colors = [[0]*C for i in range(3)]
for i in range(N):
    tmp = list(map(int, input().split()))
    for j, color in enumerate(tmp):
        num = ((i+1) + (j+1)) % 3
        colors[num][color-1] += 1
# print(colors)

data = [[0]*C for i in range(3)]


for i in range(3):
    # color[i]
    for j in range(C):
        for k in range(C):
            data[i][k] += colors[i][j] * D[j][k]
# print(data)

ans = 10**10
# for iter_ in product([0, 1, 2], repeat=C):
#     if len(set(iter_)) != C:
#         continue
#     tmp = []
#     for i, j in enumerate(iter_):
#         tmp.append(data[i][j])
#     ans = min(ans, sum(tmp))
print(ans)

Submission status: Wrong Answer

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

from itertools import product

N, C = list(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)]

colors = [[0]*C for i in range(3)]
for i in range(N):
    tmp = list(map(int, input().split()))
    for j, color in enumerate(tmp):
        num = ((i+1) + (j+1)) % 3
        colors[num][color-1] += 1
# print(colors)

data = [[0]*C for i in range(3)]


for i in range(3):
    # color[i]
    for j in range(C):
        for k in range(C):
            data[i][k] += colors[i][j] * D[j][k]
# print(data)

ans = 10**10
for iter_ in product([0, 1, 2], repeat=C):
    if len(set(iter_)) != C:
        continue
    tmp = []
    for i, j in enumerate(iter_):
        tmp.append(data[i][j])
    ans = min(ans, sum(tmp))
print(ans)

Submission status: Wrong Answer

Solution code:
from  itertools import combinations
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)]
a=[[0]*C for _ in range(3)]
for i in range(n):
	for j in range(n):
		a[(i+j)%3][c[i][j]-1]+=1
ans=10**9
for v in combinations(range(C),3):
	tmp=0
	for i in range(3):
		for j in range(C):
			tmp+=a[i][j]*d[j][v[i]]
	ans=min(ans,tmp)
print(ans)

Submission status: Wrong Answer

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

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
N,C = IL()
D = ILL(C)

data = [[0 for j in range(C)] for i in range(3)]

for i in range(N):
  temp = IL()
  for j in range(N):
    data[(i+j)%3][temp[j]-1] += 1

MIN = INF
for a in range(C):
  for b in range(a+1,C):
    for c in range(b+1,C):
      score = 0
      for j in range(C):
        score += D[j][a]*data[0][j]
        score += D[j][b]*data[1][j]
        score += D[j][c]*data[2][j]
      MIN = min(MIN,score)
print(score)

Submission status: Wrong Answer

Solution code:
from collections import Counter
from itertools import permutations

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

d = [Counter(sum([c[j][(i - j) % 3::3] for j in range(N)], []))
     for i in range(3)]
ans = 1000000
for t in permutations(range(C), 3):
    dis = 0
    for i in range(3):
        for k, v in d[i].items():
            dis += D[k][t[i]] * v
    ans = min(dis, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import itertools

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

memo = [[0 for i in range(C)]for j in range(3)]

for i in range(N):
    for j in range(N):
        cij = c[i][j]
        a = (i + j + 2) % 3
        for k in range(C):
            memo[a][k] += d[cij-1][k]

ans = 25000000


for c1, c2, c3 in itertools.permutations(range(C), 3):
    ans = min(ans, memo[0][c1] + memo[1][c2] + memo[2][c3])

print(ans)

Submission status: Wrong Answer

Solution code:
# coding: utf-8

# https://atcoder.jp/contests/abc099/tasks
# 15:00-


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

    c = [None] * N
    for i in range(N):
        c[i] = list(map(int, input().split()))
        c[i] = [x-1 for x in c[i]]  # 0-index

    STU = [[0] * C, [0] * C, [0] * C]

    for k in range(C):
        for i in range(N):
            for j in range(N):
                STU[(i+j) % 3][k] += D[c[i][j]][k]
    
    ans = 1000 * N * N
    for i in range(C):
        cand = STU[0][i]
        for j in range(C):
            if j == i:
                continue
            cand += STU[1][j]
            for k in range(C):
                if k == i or k == j:
                    continue
                cand += STU[2][k]

                if cand < ans:
                    ans = cand
    
    return ans
                    



print(main())

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from itertools import permutations

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(int,input().split())))

P = [defaultdict(int) for _ in range(3)]
for i in range(N):
    for j in range(N):
        P[(i+j)%3][c[i][j]-1] += 1

ans = 10 ** 8
for L in permutations([i for i in range(C)], 3):
    cnt = 0
    for i in range(3):
        for j in range(C):
            cnt += P[i][j] * D[j][L[i]]
    ans = min(ans, cnt)

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from itertools import permutations

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(int,input().split())))

P = [defaultdict(int) for _ in range(3)]
for i in range(N):
    for j in range(N):
        P[(i+j)%3][c[i][j]-1] += 1

ans = 10 ** 8
for L in permutations([i for i in range(C)], 3):
    cnt = 0
    for i in range(3):
        for k, v in P[i].items():
            cnt += v * D[k][L[i]]
    ans = min(ans, cnt)

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np


n, c = map(int, input().split())

a = []
b = []

for _ in range(c):
    array = list(map(int, input().split()))
    a.append(array)

for _ in range(n):
    array = list(map(int, input().split()))
    b.append(array)

d = np.array(b)
d = d.flatten()

d1 = d[0::3]
d2 = d[1::3]
d3 = d[2::3]

ans_1 = []
ans_2 = []
ans_3 = []

for i in range(c):
    sum = 0
    for j in d1:
        sum += a[j-1][i]
    ans_1.append(sum)

for i in range(c):
    sum = 0
    for j in d2:
        sum += a[j-1][i]
    ans_2.append(sum)

for i in range(c):
    sum = 0
    for j in d3:
        sum += a[j-1][i]
    ans_3.append(sum)

min_ans = 10**10

import itertools

r = list(range(c))

for i, j, k in itertools.permutations(r, 3):
    ans = ans_1[i] + ans_2[j] + ans_3[k]
    if ans < min_ans:
        min_ans = ans


print(min_ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
n,c = map(int,input().split())
d = [0]
for i in range(c):
    d.append([0] + list(map(int,input().split())))
li0 = []
li1 = []
li2 = []
for i in range(n):
    g = list(map(int,input().split()))
    for j in range(n):
        if (i + j) % 3 == 0:
            li0.append(g[j])
        if (i + j) % 3 == 1:
            li1.append(g[j])
        if (i + j) % 3 == 2:
            li2.append(g[j])
dic0 = defaultdict(int)
dic1 = defaultdict(int)
dic2 = defaultdict(int)
for i in li0:
    dic0[i] += 1
for i in li1:
    dic1[i] += 1
for i in li2:
    dic2[i] += 1 
ans = 100000000
for i in range(1,c+1):
    for j in range(1,c+1):
        for k in range(1,c+1):
            if i == j or j == k or i == k:
                continue
            x = 0
            for color in range(1,c+1):
                x += dic0[color] * d[color][i]
                x += dic1[color] * d[color][j]
                x += dic2[color] * d[color][k]
            ans = min(x,ans) 
print(ans)

Submission status: Wrong Answer

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)]
g1 = []
g2 = []
g3 = []
for i in range(N):
    for j in range(N):
        G[i][j] -= 1
        if (i+j)%3 == 0:
            g1.append(G[i][j])
        if (i+j)%3 == 1:
            g2.append(G[i][j])
        if (i+j)%3 == 2:
            g3.append(G[i][j])
# print(g1) # グループ1の色リスト
# print(g2)
# print(g3)
for k in range(C):
    for i in range(C):
        for j in range(C):
            D[i][j] = min(D[i][j], D[i][k] + D[k][j])

ans = float('inf')
for c1 in range(C):
    for c2 in range(C):
        for c3 in range(C):
            temp = 0
            if c1 == c2 or c2 == c3 or c3 == c1:
                continue
            temp += sum(D[clr_g1][c1] for clr_g1 in g1)
            temp += sum(D[clr_g2][c2] for clr_g2 in g2)
            temp += sum(D[clr_g3][c3] for clr_g3 in g3)
            ans = min(ans,temp)
print(ans)

Submission status: Wrong Answer

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

ans = float('inf')
for i in range(C):
    for j in range(C):
        if i == j:
            continue
        res = 0
        for k in range(C):
            if i == k or j == k:
                continue
            for l in range(C):
                res += D[l][i] * t[0][l]
                res += D[l][j] * t[1][l]
                res += D[l][k] * t[2][l]
            ans = min(ans, res)
print(ans)

Submission status: Wrong Answer

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

n, c = [int(x) for x in input().split()]

d_list = [[int(x) for x in input().split()] for _ in range(c)]
c_ = [[int(x) for x in input().split()] for _ in range(n)]

mod_0 = [0] * c
mod_1 = [0] * c
mod_2 = [0] * c

for i in range(n):
    for j in range(n):
        if (i + j) % 3 == 0:
            m = mod_0
        elif (i + j) % 3 == 1:
            m = mod_1
        else:
            m = mod_2
        for k in range(c):
            m[k] += d_list[c_[i][j] - 1][k]

ans = 10 ** 18

for i in range(c):
    for j in range(i + 1, c):
        for k in range(j + 1, c):
            print(i, j, k)
            a = mod_0[i] + mod_1[j] + mod_2[k]
            b = mod_0[i] + mod_1[k] + mod_2[j]
            c__ = mod_0[j] + mod_1[i] + mod_2[k]
            d = mod_0[j] + mod_1[k] + mod_2[i]
            e = mod_0[k] + mod_1[i] + mod_2[j]
            f = mod_0[k] + mod_1[j] + mod_2[i]
            ans = min(ans, a, b, c__, d, e, f)

print(ans)

Submission status: Wrong Answer

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

n, c = [int(x) for x in input().split()]

d_list = [[int(x) for x in input().split()] for _ in range(c)]
c_ = [[int(x) for x in input().split()] for _ in range(n)]

mod_0 = [0] * c
mod_1 = [0] * c
mod_2 = [0] * c

for i in range(n):
    for j in range(n):
        if (i + j) % 3 == 0:
            m = mod_0
        elif (i + j) % 3 == 1:
            m = mod_1
        else:
            m = mod_2
        for k in range(c):
            m[k] += d_list[c_[i][j] - 1][k]

ans = 10 ** 18
print(c)
for i in range(c):
    for j in range(i + 1, c):
        for k in range(j + 1, c):
            print(i, j, k)
            a = mod_0[i] + mod_1[j] + mod_2[k]
            b = mod_0[i] + mod_1[k] + mod_2[j]
            c__ = mod_0[j] + mod_1[i] + mod_2[k]
            d = mod_0[j] + mod_1[k] + mod_2[i]
            e = mod_0[k] + mod_1[i] + mod_2[j]
            f = mod_0[k] + mod_1[j] + mod_2[i]
            ans = min(ans, a, b, c__, d, e, f)

print(ans)

Submission status: Wrong Answer

Solution code:
n, c = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
s = [list(map(int, input().split())) for _ in range(n)]
c0 = [[0 for _ in range(c)] for _ in range(3)]
c1 = [[0 for _ in range(c)] for _ in range(3)]
for i in range(n):
    for j in range(n):
        if (i + j) % 3 == 0:
            c0[0][s[i][j] - 1] += 1
        elif (i + j) % 3 == 1:
            c0[1][s[i][j] - 1] += 1
        elif (i + j) % 3 == 2:
            c0[2][s[i][j] - 1] += 1
for i in range(3):
    for j in range(c):
        for k in range(c):
            c1[i][j] += d[k][j] * c0[i][k]
c2, c3 = [], []
for i in range(3):
    c2 = []
    for j in range(3):
        x = c1[i]
        a = [min(x), x.index(min(x))]
        c2.append(a)
        c1[i][c1[i].index(min(c1[i]))] = 10 ** 9
    c3.append(c2)
ans = 10 ** 9
for i in range(3):
    for j in range(3):
        for k in range(3):
            if c3[0][i][1] != c3[1][j][1] and c3[0][i][1] != c3[2][k][1] and c3[2][j][1] != c3[2][k][1]:
                m = c3[0][i][0] + c3[1][j][0] + c3[2][k][0]
                if m < ans:
                    ans = m
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import Counter
from itertools import permutations

def main():
    N, C = map(int, input().split())
    D = [[int(x) for x in input().split()] for _ in range(C)]

    cnt = [Counter() for _ in range(3)]

    for i in range(N):
        c = [int(x)-1 for x in input().split()]
        for j in range(3):
            cnt[j].update(c[(3-(i+2)+j)%3::3])

    ans = 1000*500*500+5
    for p in permutations(range(C), 3):
        s = sum(D[k][p[j]] * v for k, v in cnt[j].items() for j in range(3))
        ans = min(ans, s)

    print(ans)

main()

Submission status: Wrong Answer

Solution code:
n, c = map(int, input().split())
cost = []
grid = []
for i in range(c):
    cost.append(list(map(int, input().split())))
for i in range(n):
    grid.append(list(map(int, input().split())))
div_3 = [[0 for i in range(c+1)] for j in range(3)]
for i in range(n):
    for j in range(n):
        div_3[(i+j+2)%3][grid[i][j]-1] += 1
ans = 10**9
for zero in range(c):
    for one in range(c):
        for two in range(c):
            if len(set([zero,one,two])) <= 2:
                continue
            cand = 0
            #3で割った余りがone,zeroとかの色で決まっている状態
            cand += sum([div_3[0][i] * cost[i][zero] for i in range(c) if i != zero])
            cand += sum([div_3[1][i] * cost[i][one]  for i in range(c) if i != one])
            cand += sum([div_3[2][i] * cost[i][two]  for i in range(c) if i != two])
            if cand == 0:
                print("{} {} {}".format(zero, one, two))
            ans = min(ans, cand)
print(ans)

Submission status: Wrong Answer

Solution code:
n,c=map(int,input().split())
D=[[0]*c for i in range(c)]
for i in range(c):
  D[i]=list(map(int,input().split()))
C=[[0]*n for i in range(n)]
for i in range(n):
  C[i]=list(map(int,input().split()))
  for j in range(n):
    C[i][j]=C[i][j]-1
A=[[0]*c for i in range(3)]
for i in range(n):
  for j in range(n):
    A[(i+j)%3][C[i][j]]+=1
ans=0
e=10**20
for i in range(c):
  for j in range(c):
    if j==i:
      continue
    for k in range(c):
      if k==i:
        continue
      if k==j:
        continue
      f=0
      for u in range(c):
        f=f+A[0][u]*D[u][i]+A[1][u]*D[u][j]+A[2][u]*D[u][k]
    if e>f:
      e=f
print(e)

Submission status: Wrong Answer

Solution code:
n,c=map(int,input().split())
D=[[0]*c for i in range(c)]
for i in range(c):
  D[i]=list(map(int,input().split()))
C=[[0]*n for i in range(n)]
for i in range(n):
  C[i]=list(map(int,input().split()))
  for j in range(n):
    C[i][j]=C[i][j]-1
A=[[0]*c for i in range(3)]
for i in range(n):
  for j in range(n):
    A[(i+j)%3][C[i][j]]+=1
ans=0
e=10**10
for i in range(c):
  x=0
  for s in range(c):
    x=x+A[0][s]*D[s][i]
  for j in range(c):
    if j==i:
      continue
    y=0
    for t in range(c):
      y=y+A[1][t]*D[t][j]
    for k in range(c):
      if k==i:
        continue
      if k==j:
        continue
      z=0
      for u in range(c):
        z=z+A[2][u]*D[u][k]
    f=x+y+z
    if e>f:
      e=f
print(e)

Submission status: Wrong Answer

Solution code:
N,C=map(int,input().split())
D=[list(map(int,input().split())) for i in range(C)]
c=[list(map(int,input().split())) for i in range(N)]
count=[[0]*C for i in range(3)]
for i in range(1,N+1):
  for j in range(1,N+1):
    count[(i+j)%3][c[i-1][j-1]-1]+=1
ans=1001
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=0
      for x in range(C):
        tmp+=D[x][i]*count[0][x]+D[x][j]*count[1][x]+D[x][k]*count[2][x]
      if ans>tmp:
        ans=tmp
print(ans)