Problem:


Score : 400 points

Problem Statement

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

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

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

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

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

Here, X \% Y represents X modulo Y.

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

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

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

Constraints

1 \leq N \leq 500

3 \leq C \leq 30

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

3

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

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

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

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

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

Sample Input 2

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

Sample Output 2

428



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


Sample output:
3

Submission status: Runtime Error

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



cost = [[0]*C for _ in range(3)]
for c in range(C):
    for g in range(3):
        if g == 0:
            cost[c][0] = sum(D[clr_g1][c] for clr_g1 in g1)
        if g == 1:
            cost[c][1] = sum(D[clr_g2][c] for clr_g2 in g2)
        if g == 2:
            cost[c][2] = sum(D[clr_g3][c] for clr_g3 in g3)



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)
            temp = cost[c1][0] + cost[c2][1] + cost[c3][2]
            ans = min(ans,temp)
print(ans)

Submission status: Runtime Error

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


cost = [[0]*C for _ in range(3)]
for c in range(C):
    for g in range(3):
        if g == 0:
            cost[c][0] = sum(D[clr_g1][c] for clr_g1 in g1)
        if g == 1:
            cost[c][1] = sum(D[clr_g2][c] for clr_g2 in g2)
        if g == 2:
            cost[c][2] = sum(D[clr_g3][c] for clr_g3 in g3)



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)
            temp = cost[c1][0] + cost[c2][1] + cost[c3][2]
            ans = min(ans,temp)
print(ans)

Submission status: Runtime Error

Solution code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <string>
#include <queue>
#include <stack>

using namespace std;

typedef long long int ll;
typedef pair<int, int> Pii;

const ll mod = 1000000007;

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);

  int n, c;
  cin >> n >> c;
  vector<vector<int> > d(c, vector<int>(c));
  for (auto &x: d) {
    for (auto &y: x) cin >> y;
  }
  vector<vector<int> > a(n, vector<int>(n));
  for (auto &x: a) {
    for (auto &y: x) {
      cin >> y;
      y--;
    }
  }

  vector<int> c0Count(c), c1Count(c), c2Count(c);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      if ((i + j) % 3 == 0) c0Count[a[i][j]]++;
      else if ((i + j) % 3 == 1) c1Count[a[i][j]]++;
      else if ((i + j) % 3 == 2) c2Count[a[i][j]]++;
    }
  }

  int ans = 1000000007;
  for (int c0 = 0; c0 < c; c0++) {
    for (int c1 = 0; c1 < c; c1++) {
      if (c0 == c1) continue;
      for (int c2 = 0; c2 < c; c2++) {
        if (c0 == c2 || c1 == c2) continue;
        int cost = 0;
        for (int i = 0; i < c; i++) {
          cost += d[i][c0] * c0Count[i];
          cost += d[i][c1] * c1Count[i];
          cost += d[i][c2] * c2Count[i];
        }
        if (cost < ans) ans = cost;
      }
    }
  }

  cout << ans << endl;

  return 0;
}

Submission status: Runtime Error

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)]
mod0 = []
mod1 = []
mod2 = []
for i in range(n):
    for j in range(n):
        # indexのずれを考慮 ((i+1)+(j+1))%3が本来のmod値
        if (i+j)%3 == 1:
            mod0.append(C[i][j]-1)
        elif (i+j)%3 == 2:
            mod1.append(C[i][j]-1)
        else:
            mod2.append(C[i][j]-1)

color_range = list(range(c))
res = float('inf')
for x,y,z in itertools.permutations(color_range):
    cnt = 0
    for i in range(len(mod0)):
        cnt += D[mod0[i]][x]
    for i in range(len(mod1)):
        cnt += D[mod1[i]][y]
    for i in range(len(mod2)):
        cnt += D[mod2[i]][z]
    res = min(cnt, res)
print(res)

Submission status: Runtime Error

Solution code:
# https://atcoder.jp/contests/abc099/tasks/abc099_d
# さまざまな合わせ技
# ダイクストラ、全探索

import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため



# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations

# from scipy.sparse.csgraph import dijkstra
# from scipy.sparse import csr_matrix, lil_matrix
# 0 まずはダイクストラでX→Yの最小コストを求めておく
# 1 座標ごとに3つのグループわけができる(n=1のときだけ場合分け
# 2 グループごとに色をカウント
# 3 各グループの色を仮定して全探索

N, C = read_ints()
D = read_matrix(C)
# D = csr_matrix(D)
# D = dijkstra(D)


# 1 座標のグループわけ
Cmap = read_matrix(N)
lsbymod = defaultdict(lambda: [])
for i in range(N):
    for j in range(N):
        lsbymod[(i + j + 2) % 3].append(Cmap[i][j] - 1)

# グループごとに色のカウント
for k, v in lsbymod.items():
    lsbymod[k] = Counter(v)

# 各グループの色を仮定して全探索


# print(D)
# print(lsbymod)


def ret_score(*arg):
    # 各仮定から違和感を計算
    ret = 0
    for i in range(3):
        for k, v in lsbymod[i].items():
            ret += v * D[k][arg[i]]
    return ret


ans = 2**63
for a, b, c in permutations(range(C), 3):
    # print(a, b, c, ret_score(a, b, c))
    ans = min(ans, ret_score(a, b, c))

print(ans)

Submission status: Runtime Error

Solution code:
# https://atcoder.jp/contests/abc099/tasks/abc099_d
# さまざまな合わせ技
# ダイクストラ、全探索

import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため



# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations

from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix, lil_matrix
# 0 まずはダイクストラでX→Yの最小コストを求めておく
# 1 座標ごとに3つのグループわけができる(n=1のときだけ場合分け
# 2 グループごとに色をカウント
# 3 各グループの色を仮定して全探索

N, C = read_ints()
D = read_matrix(C)
D = csr_matrix(D)
# D = dijkstra(D)


# 1 座標のグループわけ
Cmap = read_matrix(N)
lsbymod = defaultdict(lambda: [])
for i in range(N):
    for j in range(N):
        lsbymod[(i + j + 2) % 3].append(Cmap[i][j] - 1)

# グループごとに色のカウント
for k, v in lsbymod.items():
    lsbymod[k] = Counter(v)

# 各グループの色を仮定して全探索


# print(D)
# print(lsbymod)


def ret_score(*arg):
    # 各仮定から違和感を計算
    ret = 0
    for i in range(3):
        for k, v in lsbymod[i].items():
            ret += v * D[k, arg[i]]
    return ret


ans = 2**63
for a, b, c in permutations(range(C), 3):
    # print(a, b, c, ret_score(a, b, c))
    ans = min(ans, ret_score(a, b, c))

print(ans)

Submission status: Runtime Error

Solution code:
N, C = map(int, input().split())
INF = float("inf")
D = []
for i in range(C):
    D.append(list(map(int, input().split())))
c = []
for i in range(N):
    c.append([n - 1 for n in list(map(int, input().split()))])

# 前計算
cost = [[0 for _ in range(3)] for _ in range(C)]
for i in range(N):
    for j in range(N):
        for k in range(C):
            cost[(i + j) % 3][k] += D[c[i][j]][k]

ans = INF
for i in range(C):
    for j in range(C):
        if i == j:
            continue
        for k in range(C):
            if k in (i, j):
                continue
            ans = min(ans, cost[0][i] + cost[1][j] + cost[2][k])

print(ans)

Submission status: Runtime Error

Solution code:
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
 

int main() {
    int N, C;
    cin>>N>>C;
    int D[C][C];
    vector<int>zeroarr, onearr, twoarr;
    for(int i=0;i<C;++i){
        for(int j=0;j<C;++j){
            cin>>D[i][j];
        }
    }
    int tmp;
    for(int i=0;i<N;++i){
        for(int j=0;j<N;++j){
            cin>>tmp;
            tmp--;
            if((i+j)%3==0) zeroarr.push_back(tmp);
            else if((i+j)%3==1) onearr.push_back(tmp);
            else twoarr.push_back(tmp);
        }
    }
    vector<int> zeroscore, onescore, twoscore;
    int zerotmp;
    for(int i=0;i<C;++i){
        zerotmp = 0;
        for(int j=0;j<zeroarr.size();++j){
            zerotmp += D[zeroarr[j]][i];
        }
        zeroscore.push_back(zerotmp);
    }
    int onetmp;
    for(int i=0;i<C;++i){
        onetmp = 0;
        for(int j=0;j<onearr.size();++j){
            onetmp += D[onearr[j]][i];
        }
        onescore.push_back(onetmp);
    }
    int twotmp;
    for(int i=0;i<C;++i){
        twotmp = 0;
        for(int j=0;j<twoarr.size();++j){
            twotmp += D[twoarr[j]][i];
        }
        twoscore.push_back(twotmp);
    }
 
    int ans = 1000000;
    for(int i=0;i<C;++i){
        for(int j=0;j<C;++j){
            for(int k=0;k<C;++k){
                if(i!=j & j!=k & k!=i & ans > zeroscore[i] + onescore[j] + twoscore[k]) ans = zeroscore[i] + onescore[j] + twoscore[k];
            }
        }
    }
    cout<<ans<<endl;
}

Submission status: Runtime Error

Solution code:
import numpy as np
from itertools import *

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

lst=[[],[],[]]

for y in range(N):
    for x in range(N):
        lst[(y+x)%3].append(c[y][x])


Revalue=10**18
for Color1,Color2,Color3 in list(permutations(list(range(1,C+1)),3)):
    value=0
    for i in lst[0]:
        value+=D[i-1][Color1-1]
    for i in lst[1]:
        value+=D[i-1][Color2-1]
    for i in lst[2]:
        value+=D[i-1][Color3-1]
    Revalue=min(Revalue,value)
print(Revalue)

Submission status: Runtime Error

Solution code:
import itertools

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

for i in range(C):
    D[i]=list(map(int,input().split()))
    
for i in range(N):
    c[i]=list(map(int,input().split()))
    
hist=[[0]*3 for i in range(C)]#hist[i][j]は余りiのマスにj色のマスがいくつあるか
    
    
for i in range(N):
    for j in range(N):
        rem=(i+j+2)%3
        hist[rem][c[i][j]-1]+=1
    
ans=10**10
for cset in itertools.permutations(range(C), 3):
    temp=0
    for i in range(3):
        for j in range(C):
            temp+=hist[i][j]*D[j][cset[i]]
    ans=min(ans,temp)
    
print(ans)

Submission status: Runtime Error

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input()) # n=1
def inpm(): return map(int,input().split()) # x=1,y=2
def inpl(): return list(map(int, input().split())) # a=[1,2,3,4,5,...,n]
def inpls(): return list(input().split())  # a=['1','2','3',...,'n']
def inplm(n): return list(int(input()) for _ in range(n)) # x=[] 複数行
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)] # [[2,2,2,2],[1,1,1,1],[3,3,3,3]] 
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)]) # [[1,1,1,1],[2,2,2,2],[3,3,3,3]] 
def graph():
    n=inp()
    g=[[] for _ in range(n)]
    for i in range(n):
        a = inp()
        a -= 1
        g[i].append(a)
        g[a].append(i)
    return n,g

def main():
    n,c = inpm()
    D = inpll(c)
    a = inpll(n)
    dic1 = defaultdict(int)
    dic2 = defaultdict(int)
    dic3 = defaultdict(int)
    for i in range(n):
        for j in range(n):
            if (i+j)%3 == 0:
                dic1[a[i][j]] += 1
            elif (i+j)%3 == 1:
                dic2[a[i][j]] += 1
            elif (i+j)%3 == 2:
                dic3[a[i][j]] += 1
    ANS = 10**10
    for e in permutations(range(min(c,3))):
        if n == 2:
            [x, y] = e
            ans = 0
            for color1 in dic1:
                if color1 == x+1:
                    continue
                ans += dic1[color1] * D[color1-1][x]
            for color2 in dic2:
                if color2 == y+1:
                    continue
                ans += dic2[color2] * D[color2-1][y]
            ANS = min(ANS,ans)
        else:
            [x, y, z] = e
            ans = 0
            for color1 in dic1:
                if color1 == x+1:
                    continue
                ans += dic1[color1] * D[color1-1][x]
            for color2 in dic2:
                if color2 == y+1:
                    continue
                ans += dic2[color2] * D[color2-1][y]
            for color3 in dic3:
                if color3 == z+1:
                    continue
                ans += dic3[color3] * D[color3-1][z]
            ANS = min(ANS,ans)
    print(ANS)            

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input()) # n=1
def inpm(): return map(int,input().split()) # x=1,y=2
def inpl(): return list(map(int, input().split())) # a=[1,2,3,4,5,...,n]
def inpls(): return list(input().split())  # a=['1','2','3',...,'n']
def inplm(n): return list(int(input()) for _ in range(n)) # x=[] 複数行
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)] # [[2,2,2,2],[1,1,1,1],[3,3,3,3]] 
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)]) # [[1,1,1,1],[2,2,2,2],[3,3,3,3]] 
def graph():
    n=inp()
    g=[[] for _ in range(n)]
    for i in range(n):
        a = inp()
        a -= 1
        g[i].append(a)
        g[a].append(i)
    return n,g

def main():
    n,c = inpm()
    D = inpll(c)
    a = inpll(n)
    dic1 = defaultdict(int)
    dic2 = defaultdict(int)
    dic3 = defaultdict(int)
    for i in range(n):
        for j in range(n):
            if (i+j)%3 == 0:
                dic1[a[i][j]] += 1
            elif (i+j)%3 == 1:
                dic2[a[i][j]] += 1
            elif (i+j)%3 == 2:
                dic3[a[i][j]] += 1
    ANS = 10**10
    for e in permutations(range(min(n,3))):
        if n == 2:
            [x, y] = e
            ans = 0
            for color1 in dic1:
                if color1 == x+1:
                    continue
                ans += dic1[color1] * D[color1-1][x]
            for color2 in dic2:
                if color2 == y+1:
                    continue
                ans += dic2[color2] * D[color2-1][y]
            ANS = min(ANS,ans)
        else:
            [x, y, z] = e
            ans = 0
            for color1 in dic1:
                if color1 == x+1:
                    continue
                ans += dic1[color1] * D[color1-1][x]
            for color2 in dic2:
                if color2 == y+1:
                    continue
                ans += dic2[color2] * D[color2-1][y]
            for color3 in dic3:
                if color3 == z+1:
                    continue
                ans += dic3[color3] * D[color3-1][z]
            ANS = min(ANS,ans)
    print(ANS)            

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import numpy as np
import itertools
import sys
input = sys.stdin.readline  #文字列入力では注意！

N,C = map(int,input().split())
D = np.array([list(map(int,input().split()))for _ in range(C)], dtype=np.int64)
c = np.array([list(map(int,input().split()))for _ in range(N)], dtype=np.int64)
c0 = np.zeros(C)
c1 = np.zeros(C)
c2 = np.zeros(C)
for i in range(N):
    for j in range(N):
        if (i+j)%3 == 0:
            c0[c[i,j]-1] += 1
        if (i+j)%3 == 1:
            c1[c[i,j]-1] += 1
        if (i+j)%3 == 2:
            c2[c[i,j]-1] += 1
# c0~2はXの情報
lis = itertools.permutations([i for i in range(C)])
ans = float("inf")
for l0,l1,l2 in lis:    # l0~2はYの情報
    tmp = np.sum(D[:,l0]*c0+D[:,l1]*c1+D[:,l2]*c2, dtype=np.int64)
    ans = min(ans,tmp)
print(ans)

Submission status: Runtime Error

Solution code:
n,m=map(int,input().split())
d=[list(map(int,input().split())) for _ in range(m)]
c=[list(map(int,input().split())) for _ in range(n)]
ans0=[0]
ans1=[0]
ans2=[0]
for k in range(1,m+1):
    a0=0
    a1=0
    a2=0
    for i in range(n):
        for j in range(n):
            if (i+j+2)%3==0:
                a0+=d[c[i][j]-1][k-1]
            elif (i+j+2)%3==1:
                a1+=d[c[i][j]-1][k-1]
            else:
                a2+=d[c[i][j]-1][k-1]
    ans0.append(a0)
    ans1.append(a1)
    ans2.append(a2)
ans=float("inf")
import itertools
for x,y,z in itertools.permutations(range(1,m+1)):
    ans=min(ans,ans0[x]+ans1[y]+ans2[z])

print(ans)

Submission status: Runtime Error

Solution code:
n,c=map(int,input().split())
d=[]
for i in range(c):
  d.append(list(map(int,input().split())))
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]][i]
      elif (j+k)%3==1:
        ccount2+=d[col[j][k]][i]
      else:
        ccount3+=d[col[j][k]][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: Runtime Error

Solution code:
#D問題
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)]
for i in range(N):
    for j in range(N):
        c[i][j]-=1
    

mod3 = [[0 for i in range(C)] for j in range(3)]
for i in range(N):
    for j in range(N):
        mod3[(i+j)%3][c[i][j]]+=1
        
c3 = [[0 for i in range(3)] for j in range(3)]
for i in range(3):
    for j in range(C):
        kari = 0
        for k in range(C):#kからjへ
            kari+=mod3[i][k]*D[k][j]
        c3[i][j] = kari
        
inf = float("inf")
MIN = inf

for i in range(C):
    C1 = c3[0][i]
    for j in range(C):
        if j != i:
            C2 = c3[1][j]
            for k in range(C):
                if k != i and k != j:
                    C3 = c3[2][k]
                    MIN = min(MIN,C1+C2+C3)
                    #print(C1,C2,C3)
                
if MIN != inf:
    print(MIN)
else:
    print(0)

Submission status: Runtime Error

Solution code:
#D問題
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)]
for i in range(N):
    for j in range(N):
        c[i][j]-=1
    

mod3 = [[0 for i in range(C)] for j in range(3)]
for i in range(N):
    for j in range(N):
        mod3[(i+j)%3][c[i][j]]+=1
        
c3 = [[0 for i in range(3)] for j in range(3)]
for i in range(3):
    for j in range(C):
        kari = 0
        for k in range(C):#kからjへ
            kari+=mod3[i][k]*D[k][j]
        c3[i][j] = kari
        
inf = float("inf")
MIN = inf
for i in range(C):
    C1 = c3[0][i]
    for j in range(C):
        if j != i:
            C2 = c3[1][j]
            for k in range(C):
                if k != i and k != j:
                    C3 = c3[2][k]
                    MIN = min(MIN,C1+C2+C3)
                    #print(C1,C2,C3)

print(MIN)

Submission status: Runtime Error

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

cost = [[0] * 3 for _ in range(C)]
for p in range(C):
    for i in range(N):
        for j in range(N):
            #グループごとにかかるコストの計算
            cost[(i+j)%3][p] += D[c[i][j]][p]

res = 10 ** 9
p = [0] * 3
for p[0] in range(C):
    for p[1] in range(C):
        if p[0] == p[1]:
            continue
        for p[2] in range(C):
            if p[2] == p[0] or p[1] == p[2]:
                continue
            tmp = 0
            for i in range(3):
                tmp += cost[i][p[i]]
            res = min(res, tmp)

print(res)

Submission status: Runtime Error

Solution code:
import sys

from collections import deque
# q = deque(); q.append(x); q.appendleft(x); q.pop() -> x; q.popleft() -> x
from collections import defaultdict
# d = defaultdict(lambda: []); d[key] -> []
import heapq
# hq = []; heapq.heappush(hq, x); heapq.heappop(hq) -> x; heapq.heappushpop(hq, x) -> x
import bisect
# i = bisect.bisect_left([1,2,3,4], 1.5); i = bisect.bisect_right([4,3,2,1], 1.5)

import numpy as np
#from scipy.misc import comb

s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in ss]
ss2nnn = lambda ss: [s2nn(s) for s in ss]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [sys.stdin.readline().rstrip() for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

"""
マスは1つの色を持つ -> c[i][j]
マスは3グループのいずれかに属する -> (i+j)%3
グループは1つの色 gc を持つ、ただし他のグループと同じ色を持てない gc1 != gc2 != gc3
マス違和感 = D[マスの色][グループの色]
グループ違和感 = グループ内のマスの、マス違和感の合計 = DG[グループ色]
全体違和感 = 3グループの、グループ違和感の合計
答え = 全体違和感
"""
def main():
    N, C = i2nn()
    D = ii2nnn(C)
    c = ii2nnn(N)
    iwakanG = [[0] * C for _ in range(3)]  # グループ違和感[グループID][グループ色] = グループID/色ごとのマス違和感の計
    for i in range(N):
        for j in range(N):
            groupID = (i + j) % 3  # グループID
            cM = c[i][j] - 1  # マス色
            for cG in range(C):
                iwakanM = D[cM][cG]   # マス違和感
                iwakanG[groupID][cG] += iwakanM  # グループ違和感にマス違和感を加算
    iwakan = 1e+9
    for gc1 in range(C):
        for gc2 in range(C):
            for gc3 in range(C):
                if gc1 == gc2 or gc2 == gc3 or gc3 == gc1:
                    continue
                n = iwakanG[0][gc1] + iwakanG[1][gc2] + iwakanG[2][gc3]
                if iwakan > n:
                    iwakan = n  # 全体違和感の最小化
    print(iwakan)

main()

Submission status: Runtime Error

Solution code:
from collections import defaultdict
tot = 10**12
n,c = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(n)]
clr = [list(map(int, input().split())) for _ in range(n)]
l = [dict()]*3
for y in range(n):
  for x in range(n):
    l[(x+y)%3][clr[y][x]] += 1
for c1 in range(c):
  for c2 in range(c):
    if c1 == c2:
      continue
    for c3 in range(c):
      if c1==c3 or c2==c3:
        continue
      ctot = 0
      cl = [c1,c2,c3]
      for i in range(3):
        for x in l[i]:
          ctot += d[x-1][c[i]]*l[i][x]
      if tot > ctot:
        tot = ctot
print(tot)

Submission status: Runtime Error

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)]
CM = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]

CG = [[0]*C for _ in range(3)]
for i in range(N):
    for j in range(N):
        nc = CM[i][j] - 1
        for c in range(C):
            CG[(i+j)%3][c] += D[nc][c]
ans = 10**10
for c1, c2, c3 in permutations(range(C), 3):
    ans = min(ans, CG[c1][0] + CG[c2][1] + CG[c3][2])
print(ans)

Submission status: Runtime Error

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

ans = float("inf")

L = []
for i in range(1,C+1,3) :
    L.append([i,i+1,i+2])
    L.append([i,i+2,i+1])
    L.append([i+1,i,i+2])
    L.append([i+1,i+2,i])
    L.append([i+2,i,i+1])
    L.append([i+2,i+1,i])


for i in range(len(L)) :
    p,q,r = L[i]
    
    calc = 0
    
    for j in range(N) :
        for k in range(N) :
            if (j+k) % 3 == 0 :
                calc += D[A[j][k]-1][p-1]
            elif (j+k) % 3 == 1 :
                calc += D[A[j][k]-1][q-1]
            else :
                calc += D[A[j][k]-1][r-1]
    ans = min(ans,calc)
print(ans)

Submission status: Runtime Error

Solution code:
def sol():
    n,c=map(int,input().split())
    d=[[int(i) for i in input().split()] for i in range(c)]
    t=[[int(i) for i in input().split()] for i in range(n)]
    ans=-1
    for i in range(c**2):
        for k in range(c):
            i,j=i//c,j%c
            q=[i,j,k]
            if len(set(q))<3: continue
            chk=0
            for p in range(n**2):
                h,w=p//n,p%n
                x=(h+w+2)%3
                chk+=d[t[h][w]-1][q[x]]
            if ans==-1: ans=chk
            ans=min(ans,chk)

    print(ans)

if __name__=="__main__":
    sol()

Submission status: Runtime Error

Solution code:
def sol():
    n,c=map(int,input().split())
    d=[[int(i) for i in input().split()] for i in range(c)]
    t=[[int(i) for i in input().split()] for i in range(n)]
    ans=-1
    for i in range(c):
        for j in range(c):
            for k in range(c):
                q=[i,j,k]
                if len(set(q))<3: break
                chk=0
                for p in range(n**2):
                    h,w=p//n,p%n
                    x=(h+w+2)%3
                    chk+=d[t[h][w]-1][q[x]]
                if ans==-1: ans=chk
                ans=min(ans,chk)
             
    print(ans)

if __name__="__main__":
    sol()

Submission status: Runtime Error

Solution code:
from itertools import*
n,c=map(int,input().split())
cost=[list(map(int,input().split()))for i in range(c)]
d=[[0]*c for i in range(3)]
for i in range(n):
    for j,v in enumerate(map(int,input().split())):
        d[(i+j)%3][v-1]+=1
print(min(sum(d[j][cmb[i]]*cost[i][j]for j in range(c)for i in range(3))for cmb in permutations(range(c),3)))

Submission status: Runtime Error

Solution code:
from collections import*
from itertools import*
n,c=map(int,input().split())
cost=defaultdict(int)
for i in range(1,c+1):
    for k,v in enumerate(map(int,input().split())):
        cost[(k+1,i)]=v
#print(cost)

dwatta=defaultdict(list)
l=set()
for i in range(n):
    for j,v in enumerate(map(int,input().split())):
        mod=(i+j+2)%3
        dwatta[mod]+=[(v,(i,j))]
        l.add(v)
#print(l)
#print(dwatta) #割った値、座標、色
c=[]
for i in combinations(l,3):
    for s in permutations(i):
        ccc=0
        for k,v in dwatta.items():
            for f,t in enumerate([v]):
                for a,b in t:
                    if a!=s[f]:
                        ccc+=cost[(a,s[f])]
        c.append(ccc)
print(min(c))

Submission status: Runtime Error

Solution code:
mport collections
N , C = map(int, input().split())
ds =[list(map(int, input().split())) for i in range(C)]
cs =[list(map(int, input().split())) for i in range(N)]
c0 = collections.defaultdict(int)
c1 = collections.defaultdict(int)
c2 = collections.defaultdict(int)
for i in range(N):
    for j in range(N):
        if (i+j) % 3 == 0:
            c0[cs[i][j]] += 1
        elif (i+j) % 3 == 1:
            c1[cs[i][j]] += 1
        else:
            c2[cs[i][j]] += 1
            
d = 10**9
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
            d0 = 0
            for l in c0:
                if l != i:
                    d0 += c0[l] * ds[l-1][i]
            for l in c1:
                if l != j:
                    d0 += c1[l] * ds[l-1][j]
            for l in c2:
                if l != k:
                    d0 += c2[l] * ds[l-1][k]
            if d > d0:
                d = d0
print(d)

Submission status: Runtime Error

Solution code:
import copy
N , C = map(int, input().split())
ds =[list(map(int, input().split())) for i in range(C)]
cs =[list(map(int, input().split())) for i in range(N)]
c0 = []
c1 = []
c2 = []
for i in range(N):
    for j in range(N):
        if (i+j) % 3 == 0:
            c0.append(cs[i][j])
        elif (i+j) % 3 == 1:
            c1.append(cs[i][j])
        else:
            c2.append(cs[i][j])
d = 10**9
l0 = len(c0)
l1 = len(c1)
l2 = len(c2)
for i in range(C):
    d0 = 0
    for l in range(l0):
         if (c0[l]-1) != i:
            d0 += ds[c0[l]-1][i]
    for j in range(C):
        if i == j:
            continue
        d1 = copy,copy(d0)
        for h in range(l1):
            if (c1[h]-1) != j:
                d1 += ds[c1[h]-1][j]
        for k in range(C):
            if i == k or j == k:
                continue
            d2 = copy.copy(d1)
            for l in range(l2):
                if (c2[l]-1) != k:
                    d2 += ds[c2[l]-1][k]
            if d > d2:
                d = d2
print(d)