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:
from itertools import combinations, permutations

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

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

remains = {0: [], 1: [], 2: []} 

for i in range(1, N+1):
    line = list(map(int, input().split()))
    for j in range(N):
        remains[(i+j+1)%3].append(line[j])

INF = 65535

def recolor(x, y): 
    return D[x-1][y-1]

memo = {0: {}, 1: {}, 2: {}} 

answer = INF 
for choice in permutations(list(range(1, C+1)), 3): 
    _answer = 0 
    for i in range(3):
        total = memo[i][choice[i]] if choice[i] in memo[i] else sum([recolor(r, choice[i]) for r in remains[i] if choice[i] != r])
        memo[i][choice[i]] = total
        _answer += total 
    answer = min(answer, _answer)

print(answer)

Submission status: Wrong Answer

Solution code:
import numpy as np
buf = input().split()
N = int(buf[0])
C = int(buf[1])
D = np.zeros((C, C))
for i in range(C):
	buf = input().split()
	for j in range(C):
		D[i][j] = int(buf[j])
		
c = np.zeros(3)
for i in range(2, N+2):
	c[(i%3)] += i-1
for i in range(N+2, 2*N+1):
	c[(i%3)] += N-1-(i-(N+2))
	
grid = -np.ones((3, int(np.max(c))))
groopcount = np.zeros(3)
for i in range(N):
	buf = input().split()
	for j in range(N):
		groop = (i+1+j+1)%3
		grid[groop][int(groopcount[groop])] = int(buf[j])-1
		groopcount[groop] += 1
#print(grid)
iwakan = np.zeros((3, C))

for groop in range(3):
	for color in range(C):
		for i in range(int(c[groop])):
			iwakan[groop][color] += D[int(grid[groop][i])][color]
#print(iwakan)

miniwakan = np.zeros((3, 3))
cminiwakan = np.zeros((3, 3))
for groop in range(3):
	buf = iwakan[groop]
	for best in range(3):
		mcolor = np.argmin(buf)
		miniwakan[groop][best] = buf[mcolor]
		cminiwakan[groop][best] = mcolor
		buf[mcolor] = 1000*c[groop]
#print(miniwakan)
#print(cminiwakan)
min = 1000*np.max(c)
for i in range(3):
	for j in range(3):
		for k in range(3):
			bufmin = miniwakan[0][i] + miniwakan[1][j] + miniwakan[2][k]
			c0 = cminiwakan[0][i]
			c1 = cminiwakan[1][j]
			c2 = cminiwakan[2][k]
			if((c0!=c1) and (c0!=c2) and (c1!=c2) and bufmin<min):
				min = bufmin

print(int(min))
					
			

# your code goes here

Submission status: Wrong Answer

Solution code:
import numpy as np
buf = input().split()
N = int(buf[0])
C = int(buf[1])
D = np.zeros((C, C))
for i in range(C):
	buf = input().split()
	for j in range(C):
		D[i][j] = int(buf[j])
		
c = np.zeros(3)
for i in range(2, N+2):
	c[(i%3)] += i-1
for i in range(N+2, 2*N+1):
	c[(i%3)] += N-1-(i-(N+2))
	
grid = -np.ones((3, int(np.max(c))))
groopcount = np.zeros(3)
for i in range(N):
	buf = input().split()
	for j in range(N):
		groop = (i+1+j+1)%3
		grid[groop][int(groopcount[groop])] = int(buf[j])-1
		groopcount[groop] += 1
#print(grid)
iwakan = np.zeros((3, C))

for groop in range(3):
	for color in range(C):
		#print(c3 + ((N*N)%3)//(groop+1))
		for i in range(int(c[groop])):
			#print(groop, color, i)
			#print(grid[groop][i])
			#print(D[int(grid[groop][i]-1)][color])
			iwakan[groop][color] += D[int(grid[groop][i])][color]
#print(iwakan)

miniwakan = np.zeros((3, 3))
cminiwakan = np.zeros((3, 3))
for groop in range(3):
	buf = iwakan[groop]
	for best in range(3):
		miniwakan[groop][best] = np.min(buf)
		mcolor = np.argmin(buf)
		cminiwakan[groop][best] = mcolor
		buf[mcolor] = 1000*c[groop]
#print(miniwakan)
#print(cminiwakan)
min = 1000*np.max(c)
for i in range(3):
	for j in range(3):
		for k in range(3):
			bufmin = miniwakan[0][i] + miniwakan[1][j] + miniwakan[2][k]
			c0 = cminiwakan[0][i]
			c1 = cminiwakan[1][j]
			c2 = cminiwakan[2][k]
			if((c0!=c1) and (c0!=c2) and (c1!=c2) and bufmin<min):
				min = bufmin

print(int(min))
					
			

# your code goes here

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
from itertools import permutations
N, C = map(int, input().split())
D = [int(_) for c in range(C) for _ in input().split()]

table = [0] * C * 3
for i, g in enumerate([int(_) for n in range(N) for _ in input().split()]):
    for c in range(C):
        table[i % 3 * C + c] += D[C * (g - 1) + c]


def cost(comb):
    return table[C * 0 + comb[0]] + table[C * 1 + comb[1]] + table[C * 2
                                                                   + comb[2]]


combs = permutations(range(C), 3)
min_cst = cost(min(combs, key=lambda comb: cost(comb)))
print(min_cst)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
from itertools import permutations
N, C = map(int, input().split())
D = [int(_) for c in range(C) for _ in input().split()]
G = [int(_) for n in range(N) for _ in input().split()]

table = [0] * C * 3
for i in range(N * N):
    for c in range(C):
        table[i % 3 * C + c] += D[C * (G[i] - 1) + c]


def cost(comb):
    return table[C * 0 + comb[0]] + table[C * 1 + comb[1]] + table[C * 2
                                                                   + comb[2]]


combs = permutations(range(C), 3)
min_cst = cost(min(combs, key=lambda comb: cost(comb)))
print(min_cst)

Submission status: Wrong Answer

Solution code:
import numpy as np
N, C = map(int, input().split())
D = np.array(list(map(int, input().split())), dtype=int)
for i in range(C-1):
    D = np.vstack((D, np.array(list(map(int, input().split())), dtype=int)))
Z = np.array(list(map(int, input().split())), dtype=int)
for i in range(N-1):
    Z = np.vstack((Z, np.array(list(map(int, input().split())), dtype=int)))
num = np.zeros((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.dot(num, D.T)
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: Wrong Answer

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

for seq in [[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]]:
  s=0
  for i in range(N):
    for j in range(N):
      b=i%3
      p=c[i][j]
      if p != seq[(j+b)%3] + 1:
        s+=D[p-1][seq[(j+b)%3]]
  if s<x:
    x=s

print(x)

Submission status: Wrong Answer

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

for seq in [[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]]:
  for b1 in range(3):
    s=0
    for i in range(N):
      for j in range(N):
        b2=i%3
        p=c[i][j]
        if p != seq[(j+b1+b2)%3] + 1:
          s+=D[p-1][seq[(j+b1+b2)%3]]
    if s<x:
      x=s

print(x)

Submission status: Wrong Answer

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

for b1 in range(3):
  s=0
  for i in range(N):
    for j in range(N):
      b2=i%3
      p=c[i][j]
      if p != (j+b1+b2)%3 + 1:
        s+=D[p-1][(j+b1+b2)%3]
  if s<x:
    x=s

print(x)

Submission status: Wrong Answer

Solution code:
x=input().split()
n=int(x[0])
c=int(x[1])
dlist=[]
clist=[]
for i in range (c):
    a=input().split()
    for i in a:
        dlist.append(int(i))
for i in range (n):
    a=input().split()
    for i in a:
        clist.append(int(i))
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=2
y3=3
mini=99999999999999999999
while y<=c:
    cost=0
    for i in list1:
        if i!=y:
            cost=cost+dlist[(i-1)*c+y-1]
            #print(cost)
    while y2<=c:
        if y2==y:
            y2=y2+1
        if y2>c:
            break
        for i in list2:
            if i!=y2:
                cost=cost+dlist[(i-1)*c+y2-1]
                #print(cost)
        while y3<=c:
            if y3==y or y3==y2:
                y3=y3+1
            if y3==y or y3==y2:
                y3=y3+1
            if y3>c:
                break
            for i in list3:
                if i!=y3:
                    cost=cost+dlist[(i-1)*c+y3-1]
            mini=min(mini,cost)
            #print(y,y2,y3,mini)
            y3=y3+1
        y2=y2+1
        y3=1
    y=y+1
    y2=1
print(mini)

Submission status: Wrong Answer

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

    group = [[0 for i in range(c)], [0 for i in range(c)], [0 for i in range(c)]]
    for i in range(n):
        for j in range(n):
            for color in range(c):
                group[(i+j) % 3][color] += d[grid[i][j]-1][color]

    min_cost = 1000 * 25000 + 1
    for i in range(c):
        for j in range(c):
            for k in range(c):
                if i != j and j != k and k != i:
                    min_cost = min(group[0][i]+group[1][j]+group[2][k], min_cost)

    print(min_cost)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, C = map(int, input().split())
Dij =[]
cij =[]

for i in range(C):
    tmp = list(map(int, input().split()))
    Dij.append(tmp)
for i in range(N):
    tmp = list(map(int, input().split()))
    cij.append(tmp)


std =[]
for i in range(0, 3):
    for j in [(i+1)%3, (i+2)%3]:
        tmp2 =[]
        k = 3 - (i + j)
        for l in range(N):
            tmp1 =[]
            for m in range(N):
                if (l + 1 + m + 1) % 3 == 1:
                    tmp1.append(i+1)
                elif (l + 1 + m + 1) % 3 == 2:
                    tmp1.append(j+1)
                elif (l + 1 + m + 1) % 3 == 0:
                    tmp1.append(k+1)
            tmp2.append(tmp1)
        std.append(tmp2)

diff = []
for k in range(len(std)):
    difference = 0
    for i in range(N):
        for j in range(N):
            if cij[i][j] != std[k][i][j]:
                difference += Dij[cij[i][j]-1][std[k][i][j]-1]
    diff.append(difference)

print(min(diff))

Submission status: Wrong Answer

Solution code:
N, C = map(int, input().split())
Dij =[]
cij =[]

for i in range(C):
    tmp = list(map(int, input().split()))
    Dij.append(tmp)
for i in range(N):
    tmp = list(map(int, input().split()))
    cij.append(tmp)


std =[]
for i in range(0, 3):
    for j in [(i+1)%3, (i+2)%3]:
        tmp2 =[]
        k = 3 - (i + j)
        for l in range(N):
            tmp1 =[]
            for m in range(N):
                if (l + 1 + m + 1) % 3 == 1:
                    tmp1.append((i+1)%3)
                elif (l + 1 + m + 1) % 3 == 2:
                    tmp1.append((j+1)%3)
                elif (l + 1 + m + 1) % 3 == 0:
                    tmp1.append((k+1)%3)
            tmp2.append(tmp1)
        std.append(tmp2)

diff = []
for k in range(len(std)):
    difference = 0
    for i in range(N):
        for j in range(N):
            if cij[i][j] != std[k][i][j]:
                difference += Dij[cij[i][j]-1][std[k][i][j]-1]
    diff.append(difference)

print(min(diff))

Submission status: Wrong Answer

Solution code:
N, C = map(int, input().split())
Dij =[]
cij =[]

for i in range(C):
    tmp = list(map(int, input().split()))
    Dij.append(tmp)
for i in range(N):
    tmp = list(map(int, input().split()))
    cij.append(tmp)


std =[]
for i in range(0, 3):
    for j in [(i+1)%3, (i+2)%3]:
        tmp2 =[]
        k = 3 - (i + j)
        for l in range(N):
            tmp1 =[]
            for m in range(N):
                if (l + 1 + m + 1) % 3 == 1:
                    tmp1.append(i)
                elif (l + 1 + m + 1) % 3 == 2:
                    tmp1.append(j)
                elif (l + 1 + m + 1) % 3 == 0:
                    tmp1.append(k)
            tmp2.append(tmp1)
        std.append(tmp2)

diff = []
for k in range(len(std)):
    difference = 0
    for i in range(N):
        for j in range(N):
            if cij[i][j] != std[k][i][j]:
                difference += Dij[cij[i][j]-1][std[k][i][j]-1]
    diff.append(difference)
print(min(diff))

Submission status: Wrong Answer

Solution code:
def main():
#    N, C = 2, 3
#    D = [[0, 1, 1],
#         [1, 0, 1],
#         [1, 4, 0]]
#    c_init = [[1, 2],
#              [3, 3]]
    
#    N, C = 4, 3
#    D = [[0, 12, 71],
#         [81, 0, 53],
#         [14, 92, 0]]
#    c_init = [[1, 1, 2, 1],
#              [2, 1, 1, 2],
#              [2, 2, 1, 3],
#              [1, 1, 2, 2]]
    
    N, C = map(int, input().split())
    D = []
    for i in range(C):
        D.append(list(map(int, input().split())))
        
    c_init = []
    for i in range(N):
        c_init.append(list(map(int,input().split())))
    
    group0 = [0]*C
    group1 = [0]*C
    group2 = [0]*C
    
    
    #1. 各グループに何色がどれだけあるかチェック
    for i in range(N):
        for j in range(N):
            if (i+j+2)%3==0:
                group0[c_init[i][j] - 1] += 1
            elif (i+j+2)%3 == 1:
                group1[c_init[i][j] - 1] += 1
            else:
                group2[c_init[i][j] - 1] += 1
                
    print(group0)
    print(group1)
    print(group2)
    
    #2. 違和感の大きさをチェック
    iwakan =[]
    for color0 in range(C):
        for color1 in range(C):
            if color1 == color0:
                continue
            
            for color2 in range(C):
                if color2==color0 or color2==color1:
                    continue
                
                iwakan_temp = 0
                for colorN in range(C):
                    iwakan_temp += group0[colorN]*D[colorN][color0]
                    iwakan_temp += group1[colorN]*D[colorN][color1]
                    iwakan_temp += group2[colorN]*D[colorN][color2]
                
                iwakan.append(iwakan_temp)
                
    print(min(iwakan))
    
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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]*(10**6) 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)

Submission status: Wrong Answer

Solution code:
import itertools

N, C = [int(x) for x in raw_input().split()]
D = []
for a in range(C):
  D.append([int(x) for x in raw_input().split()])
c = []
for i in range(N):
  c.append([int(x) for x in raw_input().split()])

cntc = []
for a in range(3):
  cntc.append([0]*C)
for i in range(N):
  for j in range(N):
    a = (i+j)%3
    b = c[i][j]-1
    cntc[a][b] += 1
costs = []
for a in range(3):
  costs.append([0]*C)
for a in range(3):
  for x in range(C):
    for y in range(C):
      costs[a][y] += D[x][y]*cntc[a][x]
mincost = 1000 * C
for cp in itertools.permutations(range(C),3):
  s = 0
  for a in range(3):
    s += costs[a][cp[a]]
  mincost = min(mincost, s)
print mincost

Submission status: Wrong Answer

Solution code:
def calc(start, c):
    _n, _tbl, _grids = n, tbl[c], grids
    ret = 0
    for i in range(start, _n - 1, 3):
        j = 0
        while i >= 0:
            # print('calc', start, c, i, j, ret)
            ret += _tbl[_grids[i][j]]
            i -= 1
            j += 1
    for j in range((start + 1 - _n % 3) % 3, _n, 3):
        i = _n - 1
        while j < _n:
            # print('calc', start, c, i, j, ret)
            ret += _tbl[_grids[i][j]]
            i -= 1
            j += 1
    return ret


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

tbl = list(zip(*tbl))
for row in grids:
    for i, k in enumerate(row):
        row[i] = k - 1

ans = float('inf')
for c0 in range(c):
    tmp = calc(0, c0)
    if ans <= tmp:
        continue
    for c1 in range(c):
        if c0 == c1:
            continue
        tmp += calc(1, c1)
        if ans <= tmp:
            continue
        for c2 in range(c):
            if c0 == c2 or c1 == c2:
                continue
            tmp += calc(2, c2)
            ans = min(ans, tmp)
print(ans)

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

Solution code:
from itertools import product
n, c = map(int, input().split())
color_costs = [map(int, input().split()) for _ in range(c)]
matrix = [map(int, input().split()) for _ in range(n)]
colord = {(i+1, j+1):cost for i, row in enumerate(color_costs)
                         for j, cost in enumerate(row)}
 
cellgroups = [[] for _ in range(3)]
for i, row in enumerate(matrix):
  for j, color in enumerate(row):
    cellgroups[(i+1+j+1)%3].append(color)
  
cc = [[(color, sum(colord[cellcolor, color] for cellcolor in cells))
	       									for color in range(1,c+1)]
      										for cells in cellgroups]
 
dd = [sorted(xs)[:3] for xs in cc]
ee = (a[1]+b[1]+c[1] for a, b, c in product(*dd) if len(set((a[0], b[0], c[0]))) == 3)
print(min(ee))

Submission status: Wrong Answer

Solution code:
from itertools import product
n, c = map(int, input().split())
color_costs = [map(int, input().split()) for _ in range(c)]
matrix = [map(int, input().split()) for _ in range(n)]
colord = {(i, j):cost for i, row in enumerate(color_costs)
                         for j, cost in enumerate(row)}

cellgroups = [[] for _ in range(3)]
for i, row in enumerate(matrix):
  for j, color in enumerate(row):
    cellgroups[(i+j)%3].append(color-1)
  
cc = [[(color, sum(colord[cellcolor, color] for cellcolor in cells))
	       									for color in range(c)]
      										for cells in cellgroups]

dd = [xs[:3] for xs in cc]
ee = (a[1]+b[1]+c[1] for a, b, c in product(*dd) if len(set((a[0], b[0], c[0]))) == 3)
print(min(ee))

Submission status: Wrong Answer

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

iwakan_min = 500001

def modthree(i, j):
	if (i + j) % 3 == 0:
		return p
	elif (i + j) % 3 == 1:
		return q
	else:
		return r

for p, q, r in permutations(range(0, C), r=3):
	iwakan = 0
	for i, j in product(range(N), repeat=2):
		iwakan += D[c[i][j] - 1][modthree(i, j)]
	if iwakan < iwakan_min:
		iwakan_min = iwakan

print(iwakan_min)

Submission status: Wrong Answer

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

choices = [[0 for x in range(C)] for x in range(3)]
for i in range(N):
    for j in range(N):
        for c in range(C):
            choices[(i+j)%3][c] += (wrongness[grid[j][i] - 1][c])

ans = 10**18
chosen = []
for i in range(C):
    chosen = [False for x in range(C)]
    chosen[i] = True
    
    for j in range(C):
        if chosen[j]:
            continue
        chosen[j] = True
        for k in range(C):
            if not chosen[k]:
                ans = min(ans,choices[0][i] + choices[1][j] + choices[2][k])

print(ans)

Submission status: Wrong Answer

Solution code:
n, c = map(int, input().split())
arrD = list(list(map(int, input().split())) for i in range(c))
arrC = list(list(map(int, input().split())) for i in range(n))

##剰余r=0,1,2で、
    ##色の出現数を確認する -> いずれかの色に統一する
        ##どの色に統一するか全パターンを実施して、違和感を算出
##和を取る

arrCCnt = []
for r in range(3):
    d = dict()
    for x in range(n):
        for y in range(n):
            d[arrC[x][y]] = 0
    arrCCnt += [d]

ret = 1000 * 500 * 500
for r in range(3):
    for i in range(n):
        for j in range(n):
            if ((i + 1) + (j + 1)) % 3 == r:
                arrCCnt[r][arrC[i][j]] += 1##色の出現数を確認

##print(arrCCnt)
for c0 in arrCCnt[0].keys():
    for c1 in arrCCnt[1].keys():
        for c2 in arrCCnt[2].keys():
            if c0 != c1 and c1 != c2 and c2 != c0:
                buf = 0
                ##print(c0,c1,c2)
                for i0 in arrCCnt[0].keys():
                    ##print(i0)
                    buf += arrD[i0 - 1][c0 - 1] * arrCCnt[0][i0]##数
                for i1 in arrCCnt[1].keys():
                    buf += arrD[i1 - 1][c1 - 1] * arrCCnt[1][i1]##数
                for i2 in arrCCnt[2].keys():
                    buf += arrD[i2 - 1][c2 - 1] * arrCCnt[2][i2]##数
                ret = min(ret, buf)
print(ret)

Submission status: Wrong Answer

Solution code:

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

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

#3色選んで違和感を求める
Iwakan = 1**10
for i in range(C):
    for j in range(C):
        if i==j:
            continue
        for k in range(C):
            if i == k or j == k:
                continue
            Iwakan = min(Iwakan,c[0][i]+c[1][j]+c[2][k])

print(Iwakan)

Submission status: Wrong Answer

Solution code:
n,c = [int(i) for i in input().split()]
effort = []
group1 = []
group2 = []
group3 = []

effort1 = []
effort2 = []
effort3 = []

color1 = [0 for i in range(c)]
color2 = [0 for i in range(c)]
color3 = [0 for i in range(c)]

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

for i in range(n):
    k = 0
    for j in input().split():
        k+=1
        tot = i+1+k
        if tot % 3 == 0:
            group1.append(int(j))
        elif tot % 3 == 1:
            group2.append(int(j))
        elif tot % 3 == 2:
            group3.append(int(j))

for i in group1:
    color1[i-1] +=1
for i in group2:
    color2[i-1] +=1
for i in group3:
    color3[i - 1] += 1

print(color1,color2,color3)

for i in range(c):
    eff = 0
    for k in range(c):
        eff += color1[k] * effort[k][i]
    effort1.append([eff,i])
for i in range(c):
    eff = 0
    for k in range(c):
        eff += color2[k] * effort[k][i]
    effort2.append([eff, i])
for i in range(c):
    eff = 0
    for k in range(c):
        eff += color3[k] * effort[k][i]
    effort3.append([eff, i])

effort1 = sorted(effort1)
effort2 = sorted(effort2)
effort3 = sorted(effort3)
print(effort1,effort2,effort3)
toteff = 10000000000000000000
for i in range(3):
    col1 = effort1[i][1]
    for k in range(3):
        col2 = effort2[k][1]
        for j in range(3):
            col3 = effort3[j][1]
            if col1 != col2 and col2 !=col3 and col1!=col3:
                print(col1,col2,col3)
                print(effort1[i][0],effort2[k][0],effort3[j][0])
                toteff = min(toteff,effort1[i][0]+effort2[k][0]+effort3[j][0])

print(toteff)

Submission status: Wrong Answer

Solution code:
N, C = map(int, raw_input().split())
D = [map(int, raw_input().split()) for _ in range(C)]
G = [map(int, raw_input().split()) for _ in range(N)]
GC = []
GC.append([0]*C)
GC.append([0]*C)
GC.append([0]*C)
for y in range(N):
  for x in range(N):
    GC[(y+x)%3][G[y][x]-1] += 1
ans = 10000000
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
      cost = 0
      for i in range(C):
        cost += GC[0][i]*D[i][a]
        cost += GC[1][i]*D[i][b]
        cost += GC[2][i]*D[i][c]
      ans = min(ans, cost)
print ans

Submission status: Wrong Answer

Solution code:
def spaceinput():
    return list(map(int,input().split(" ")))


def wariate(ary,k):
    sum=0
    for sa in ary:
        sum+=D[sa-1][k-1]
    return sum


N,C=spaceinput()


D=[]
c=[]

cols=list(range(1,C+1))


for i in range(C):
    D.append(spaceinput())

for i in range(N):
    c.append(spaceinput())

G=[[] for i in range(3)]

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


K=[[-1  for j in range(C)] for i in range(3)]

res=0
for k in range(3):
    for sc in cols:
        K[k-1][sc-1]=wariate(G[k],sc)
        continue
        if ss<minv:
            minv=ss
            ming=k
        #cols.remove(mincol)

            minv=10**6
            #mincol=-1
            ming=-1


res=10**8
def dfs(k,used,sum):
    global res
    if k==3:
        if res>sum:
            res=sum
            #print(used)
        return

    for i in range(1,C+1):
        if i in used:
            continue
        used.append(i)
        sum+=K[k][i-1]
        dfs(k+1,used,sum)
        sum-=K[k][i-1]
        used.pop()

sum=0
dfs(0,[],sum)


print(res)

Submission status: Wrong Answer

Solution code:
import random
from itertools import product

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

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

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

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

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

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

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys

N, C = [int(i) for i in input().split()]
D = {}
c = [deque(),deque(),deque()]

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

dif0={}
for i in range(C):
    i = i + 1
    tmp = 0
    for j in c[0]:
        if j != i:
            tmp += D[(j,i)]
    dif0[i] = tmp

dif1={}
for i in range(C):
    i = i + 1
    tmp = 0
    for j in c[1]:
        if j != i:
            tmp += D[(j,i)]
    dif1[i] = tmp
        
dif2={}
for i in range(C):
    i = i + 1
    tmp = 0
    for j in c[2]:
        if j != i:
            tmp += D[(j,i)]
    dif2[i] = tmp

ans = sys.maxsize
for i in dif0:
    for j in dif1:
        for k in dif2:
            tmp = i + j + k
            if tmp < ans and i != j and j != k and k != 1:
                ans = tmp
print(ans)