CodeEff/ECCO huggingface dataset:
# Original solution
graph = []

def init():
    global graph
    graph = [[False] * 26 + [True] for _ in range(27)]
    graph[26][26] = False

def atoi(c):#index
    if c == "#":
        return 26
    return ord(c) - ord("a")

def make_graph(L):
    global graph, count
    cur = 0
    L = [L[0]] + [L[i] for i in range(1, len(L)) if L[i] != L[i-1]]
    tmp = []
    for s1, s2 in zip(L, L[1:]):
        if s1[0] == s2[0]:
            tmp += [s1[1:], s2[1:]]
        else:
            if not tmp == []:
                make_graph(tmp)
            tmp = []
            graph[atoi(s2[0])][atoi(s1[0])] = True
    if not tmp == []:
        make_graph(tmp)

def check(start):
    stack = set([start])
    visited = [False] * 27
    while len(stack) != 0:
        cur = stack.pop()
        visited[cur] = True
        if graph[cur][start]:
            return False
        for i in range(27):
            if graph[cur][i] and not visited[i]:
                stack.add(i)
    return True

while True:
    n = eval(input())
    if n == 0:
        break
    L = [input() + "#" for _ in range(n)]
    init()
    make_graph(L)
    for i in range(27):
        if not check(i):
            print("no")
            break
    else:
        print("yes")

# Optimized solution
graph = []

def init():
    global graph
    graph = [[False] * 26 + [True] for _ in range(27)]
    graph[26][26] = False

def atoi(c):#index
    if c == "#":
        return 26
    return ord(c) - ord("a")

def make_graph(L):
    global graph
    cur = 0
    L = [L[0]] + [L[i] for i in range(1, len(L)) if L[i] != L[i-1]]
    tmp = []
    for s1, s2 in zip(L, L[1:]):
        if s1[0] == s2[0]:
            tmp += [s1[1:], s2[1:]]
        else:
            if not tmp == []:
                make_graph(tmp)
            tmp = []
            graph[atoi(s2[0])][atoi(s1[0])] = True
    if not tmp == []:
        make_graph(tmp)

def check(start):
    stack = set([start])
    visited = [False] * 27
    while len(stack) != 0:
        cur = stack.pop()
        visited[cur] = True
        if graph[cur][start]:
            return False
        for i in range(27):
            if graph[cur][i] and not visited[i]:
                stack.add(i)
    return True

while True:
    n = eval(input())
    if n == 0:
        break
    L = [input() + "#" for _ in range(n)]
    init()
    make_graph(L)
    for i in range(27):
        if not check(i):
            print("no")
            break
    else:
        print("yes")
# Original solution
import sys

sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  #空白なし
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  #空白あり
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし


X,Y = MI()
print(('Alice' if abs(X-Y) >= 2 else 'Brown'))


# Optimized solution
import sys
def MI(): return list(map(int,sys.stdin.readline().rstrip().split()))


X,Y = MI()
print(('Alice' if abs(X-Y) >= 2 else 'Brown'))
# Original solution
X, Y = list(map(int, input().split()))

memo = [[[-1, -1] for _ in range(X + Y + 1)] for _ in range(X + Y + 1)]
def search(x, y, person):
    if x <= 1 and y <= 1:
        return False if person == 0 else True

    if x == 2 and y == 0 or x == 0 and y == 2:
        return True if person == 0 else False

    if memo[y][x][person] != -1:
        return memo[y][x][person]

    ret = False
    for i in range(2, x + 1, 2):
        ret |= search(x - i, y + i // 2, 1 if person == 0 else 0)
    for i in range(2, y + 1, 2):
        ret |= search(x + i // 2, y - i, 1 if person == 0 else 0)

    memo[y][x][person] = ret
    return ret

ans = search(X, Y, 0)
print(('Alice' if ans else 'Brown'))

# Optimized solution
X, Y = list(map(int, input().split()))

if abs(X - Y) <= 1:
    print('Brown')
else:
    print('Alice')
# Original solution
import sys
sys.setrecursionlimit(10**9)

X, Y = list(map(int, input().split()))

def rec(x, y) :
    flg = False
    for i in range(2, x + 1, 2) :
        flg = flg or not rec(x-i, y+i//2)
    for i in range(2, y + 1, 2) :
        flg = flg or not rec(x+i//2, y-i)
        
    return flg
    
if rec(X, Y) :
    print('Alice')
else :
    print('Brown')

# Optimized solution
X, Y = list(map(int, input().split()))

if abs(X-Y) <= 1 :
    print('Brown')
else :
    print('Alice')
# Original solution
#!/usr/bin/env python
# -*- coding: utf-8 -*-

A, B  = list(map(int, input().split()))

while True:
	if A == 0 and B == 0:
		print("Brown")
		break
	
	while A > 1:
		A -= 2
		B += 1
	
	while B > 1:
		B -= 2
		A += 1
	
	if A == 1 and B == 0:
		print("Brown")
		break
	elif A == 0 and B == 1:
		print("Alice")
		break



# Optimized solution
#!/usr/bin/env python
# -*- coding: utf-8 -*-

A, B  = list(map(int, input().split()))

if abs(A - B) < 2:
	print("Brown")
else:
	print("Alice")
# Original solution
import sys
from collections import deque
readline = sys.stdin.readline
n = int(readline())
li = list(map(int, readline().split()))
def square(P):
    G = []
    L = deque()
    for i, v in enumerate(P):
        if not L:
            L.append((i, v))
            continue
        if v > L[-1][1]:
            L.append((i, v))
        elif v < L[-1][1]:
            k = i - 1
            while L and v < L[-1][1]:
                a = L.pop()
                G.append((k - a[0] + 1) * a[1])
            L.append((a[0], v))
    while L:
        a = L.pop()
        G.append((len(P) - a[0]) * a[1])
    return max(G)
print((square(li)))

# Optimized solution
import sys
from collections import deque
readline = sys.stdin.readline
n = int(readline())
li = list(map(int, readline().split()))
def square(P):
    G = []
    L = deque()
    for i, v in enumerate(P):
        if not L:
            L.append((i, v))
            continue
        if v > L[-1][1]:
            L.append((i, v))
        elif v < L[-1][1]:
            k = i - 1
            while L and v < L[-1][1]:
                a = L.pop()
                G.append((k - a[0] + 1) * a[1])
            L.append((a[0], v))
    while L:
        a = L.pop()
        G.append((n - a[0]) * a[1])
    return max(G)
print((square(li)))
# Original solution
n = int(eval(input()))
hs = list(map(int, input().split()))
maxh = max(hs)
dp = [-1] * (maxh + 1)
ans = 0

for i, h in enumerate(hs):
    for j in range(h + 1):
        if dp[j] == -1:
            dp[j] = i
    for j in range(h + 1, maxh + 1):
        if dp[j] != -1:
            ans = max(ans, j * (i - dp[j]))
            dp[j] = -1
ans = max(ans, max((n - i) * j for j, i in enumerate(dp) if i != -1))

print(ans)

# Optimized solution
n = int(eval(input()))
hs = list(map(int, input().split()))
stack = []
ans = 0

for i, h in enumerate(hs):
    j = -1
    while stack and stack[-1][1] > h:
        j, h2 = stack.pop()
        ans = max(ans, (i - j) * h2)
    if not stack or stack[-1][1] < h:
        stack.append((i if j == -1 else j, h))
ans = max(ans, max((n - j) * h2 for j, h2 in stack))

print(ans)
# Original solution
import sys

def solve(N, R):
    print((R if N >= 10 else R + 100 * (10 - N)))

if __name__ == '__main__':
    N, R = list(map(int, sys.stdin.readline().strip().split(" ")))
    solve(N, R)

# Optimized solution
import sys

N, R = list(map(int, sys.stdin.readline().split()))
print((R if 10 <= N else R + 100 * (10 - N)))
# Original solution
N, R = list(map(int, input().split()))
if N >= 10:
    print(R)
else:
    print((R+(100*(10-N))))

# Optimized solution
N, R= list(map(int, input().split()))

if N <= 10:
    print((R+(100*(10-N))))
else:
    print(R)
# Original solution
import sys

sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  #空白なし
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  #空白あり
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし


N,R = MI()
print((R if N >= 10 else R+100*(10-N)))


# Optimized solution
import sys
def MI(): return list(map(int,sys.stdin.readline().rstrip().split()))


N,R = MI()
print((R if N >= 10 else R+100*(10-N)))
# Original solution
n, r = list(map(int, input().split()))

if n >= 10:
    print(r)
else:
    print((r + 100*(10-n)))


# Optimized solution
import sys

stdin = sys.stdin

ni = lambda: int(ns())
ns = lambda: stdin.readline().rstrip()
na = lambda: list(map(int, stdin.readline().split()))

# code here
N, R = na()


if N >= 10:
    print(R)
else:
    print((R + 100*(10-N)))
# Original solution
n,r = list(map(int,input().split()))
rate = 100*(10 - n)
if n >= 10:
    print(r)
elif n < 10:
    rate2 = rate + r
    print((str(rate2)))

# Optimized solution
n,r = list(map(int,input().split()))
rate = 100*(10 - n)
if n >= 10:
    print(r)
else:
    rate2 = rate + r
    print((str(rate2)))
# Original solution
#!/usr/bin/env python3
k,n = list(map(int,input().split()))
if k >= 10:
    print(n)
else:
    print((n+100*(10-k)))

# Optimized solution
#!/usr/bin/env python3
n,r = list(map(int,input().split()))
print((r+100*max(0,10-n)))
# Original solution
n,r=list(map(int,input().split()))
if n<10:
	print((r+100*(10-n)))
else:
	print(r)

# Optimized solution
n,r=list(map(int,input().split()));print((r+(n<10)*100*(10-n)))
# Original solution
N, R = list(map(int, input().split()))
print((R+max(0, 10-N)*100))


# Optimized solution
N, R = list(map(int, input().split()))

if N >= 10:
    print(R)
else:
    print((R+100*(10-N)))
# Original solution
import math
import itertools
import fractions
import heapq
import collections
import bisect
import sys
import copy

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

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return eval(input())

n,r = LI()
if n<10:
    print((r+(100*(10-n))))
else:
    print(r)

# Optimized solution
n,r = list(map(int,input().split()))

if n>=10:
    print(r)
else:
    t = 100*(10-n)
    print((r+t))
# Original solution
n, r = list(map(int, input().split()))

ans = r
if n < 10:
	ans += 100*(10-n)
print(ans)

# Optimized solution
n, r = list(map(int, input().split()))

if n >= 10:
	ans = r
else:
#	r = ans - 100 * (10 - n)
	ans = r + 100 * (10 - n)
print(ans)
# Original solution
n,r=list(map(int,input().split()))
if n>=10:
    print(r)
else:
    ans=r+100*(10-n)
    print(ans)

# Optimized solution
n, r = list(map(int, input().split()))
if n >= 10:
    print(r)
else:
    print((r + 100 * (10 - n)))
# Original solution
#!/usr/bin/env python3
import sys
import itertools 

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

    print(answer)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    D = [[int(next(tokens)) for _ in range(C)] for _ in range(C)]  # type: "List[List[int]]"
    c = [[int(next(tokens)) for _ in range(N)] for _ in range(N)]  # type: "List[List[int]]"
    solve(N, C, D, c)

if __name__ == '__main__':
    main()


# Optimized solution
#!/usr/bin/env python3
import sys
import itertools 

def solve(N: int, C: int, D: "List[List[int]]", c: "List[List[int]]"):
    answer = 10**9

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


    for i in range(1,N+1):
        for j  in range(1,N+1):
            cost[(i+j)%3][c[i-1][j-1]-1] += 1

    for i in range(C):
        for j in range(C):
            for k in range(C):
                if i==j or j==k or k==i:
                    continue
                a = 0
                for index in range(C):
                    a += cost[0][index]*D[index][i]
                    a += cost[1][index]*D[index][j]
                    a += cost[2][index]*D[index][k]
                
                answer = min(a,answer)

    print(answer)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    D = [[int(next(tokens)) for _ in range(C)] for _ in range(C)]  # type: "List[List[int]]"
    c = [[int(next(tokens)) for _ in range(N)] for _ in range(N)]  # type: "List[List[int]]"
    solve(N, C, D, c)

if __name__ == '__main__':
    main()
# Original solution
import sys
from itertools import permutations
N, C = list(map(int, sys.stdin.readline().rstrip().split()))

d = []
for _ in range(C):
    d.append(tuple(map(int, sys.stdin.readline().rstrip().split())))

r_0 = []
r_1 = []
r_2 = []
for i in range(N):
    g = list(map(int, sys.stdin.readline().rstrip().split()))
    for j in range(N):
        if (i + j + 2) % 3 == 0:
            r_0.append(g[j])
        elif (i + j + 2) % 3 == 1:
            r_1.append(g[j])
        else:
            r_2.append(g[j])

ans = 10**18
for c_1, c_2, c_3 in permutations(list(range(1, C + 1)), 3):
    total = 0
    for r in r_0:
        total += d[r - 1][c_1 - 1]
    for r in r_1:
        total += d[r - 1][c_2 - 1]
    for r in r_2:
        total += d[r - 1][c_3 - 1]
    ans = min(ans, total)
print(ans)

# Optimized solution
import sys
from itertools import permutations
N, C = list(map(int, sys.stdin.readline().rstrip().split()))

d = []
for _ in range(C):
    d.append(tuple(map(int, sys.stdin.readline().rstrip().split())))

r_0 = []
r_1 = []
r_2 = []
for i in range(N):
    g = list(map(int, sys.stdin.readline().rstrip().split()))
    for j in range(N):
        if (i + j) % 3 == 0:
            r_0.append(g[j])
        elif (i + j) % 3 == 1:
            r_1.append(g[j])
        else:
            r_2.append(g[j])

def get_cost(r):
    cost = [0] * (C + 1)
    for c in range(1, C + 1):
        for i in r:
            cost[c] += d[i - 1][c - 1]

    return cost

cost_0 = get_cost(r_0)
cost_1 = get_cost(r_1)
cost_2 = get_cost(r_2)

ans = 10**18
for c_0, c_1, c_2 in permutations(list(range(1, C + 1)), 3):
    total = cost_0[c_0] + cost_1[c_1] + cost_2[c_2]
    ans = min(ans, total)
print(ans)
# Original solution
n,c = list(map(int,input().split()))

D_list = [[int(i) for i in input().split()] for _ in range(c)]
c_list = [[int(i) for i in input().split()] for _ in range(n)]


ans = 10 ** 10
for i in range(1,c**3):
    x=i%c
    y=(i%c**2)//c
    z=i//c**2
    if x==y or y==z or z==x:
        continue
    else:
        color=[x,y,z]
        count = 0
        for a in range(n):
            for b in range(n):
                if color[(a+b+2)%3] != c_list[b][a]-1:
                    count+=D_list[c_list[b][a]-1][color[(a+b+2)%3]]
        if count < ans:
            ans = count

print(ans)


# Optimized solution
n,c = list(map(int,input().split()))

D_list = [[int(i) for i in input().split()] for _ in range(c)]
c_list = [[int(i) for i in input().split()] for _ in range(n)]

c_num=[[0 for _ in range(3)] for __ in range(c)]

for a in range(n):
    for b in range(n):
        c_num[c_list[b][a]-1][(a+b+2)%3] += 1


ans = 10 ** 10
for i in range(1,c**3):
    x=i%c
    y=(i%c**2)//c
    z=i//c**2
    if x==y or y==z or z==x:
        continue
    else:
        color=[x,y,z]
        count = 0
        for s in range(3):
            for t in range(c):
                count += c_num[t][s] *D_list[t][color[s]]

        if count < ans:
            ans = count

print(ans)
# Original solution
# divide this matrix into 3 groups according to the remainder
# then consider the cost

from itertools import permutations

N, C = [int(elem) for elem in input().split(' ')]
D_matrix = [[int(elem) for elem in input().split(' ')] for _ in range(C)]
assert len(D_matrix) == C
assert len(D_matrix[0]) == C
c_matrix = [[int(elem) for elem in input().split(' ')] for _ in range(N)]
assert len(c_matrix) == N
assert len(c_matrix[0]) == N

# grouping
# O(N^2)
mod_0, mod_1, mod_2 = [], [], []
for i in range(N):
    for j in range(N):
        if (i + j) % 3 == 0:
            mod_0.append((i, j))
        elif (i + j) % 3 == 1:
            mod_1.append((i, j))
        else:
            mod_2.append((i, j))

# O(C^3 * N^2)
# muda
# only considering top 3 transitions is enough?
min_cost = float('inf')
for colors in permutations(list(range(C)), 3):
    total_cost = 0
    for idx_color, mod in enumerate((mod_0, mod_1, mod_2)):
        for i, j in mod:
            color = c_matrix[i][j] - 1
            total_cost += D_matrix[color][colors[idx_color] - 1]
    min_cost = min(min_cost, total_cost)

print(min_cost)

# Optimized solution
from itertools import permutations

N, C = [int(elem) for elem in input().split(' ')]
D_matrix = [[int(elem) for elem in input().split(' ')] for _ in range(C)]
assert len(D_matrix) == C
assert len(D_matrix[0]) == C
c_matrix = [[int(elem) for elem in input().split(' ')] for _ in range(N)]
assert len(c_matrix) == N
assert len(c_matrix[0]) == N

# grouping
# O(N^2)
mod_list = [[] for _ in range(3)]
for i in range(N):
    for j in range(N):
        mod_list[(i + j) % 3].append((i, j))

# O(N^2)
mod_color_list = [[0] * C for _ in range(3)]
for k, mod in enumerate(mod_list):
    for i, j in mod:
        mod_color_list[k][c_matrix[i][j] - 1] += 1

# O(C^3 * N^2) -> O(C^4)
min_cost = float('inf')
for colors in permutations(list(range(C)), 3):
    total_cost = 0
    for color, mod_color in zip(colors, mod_color_list):
        total_cost += sum([D_matrix[X][color] * mod_color[X] for X in range(C)])
    min_cost = min(min_cost, total_cost)

print(min_cost)
# Original solution
# ABC099D - Good Grid
import sys
input = sys.stdin.readline

from collections import Counter
from itertools import product


def main():
    N, C = list(map(int, input().split()))
    D = [0] + list([0] + list(map(int, input().split())) for _ in range(C))
    grid = tuple(tuple(map(int, input().split())) for _ in range(N))
    cost = [Counter() for _ in range(3)]
    for i, g in enumerate(grid):
        for j in range(3):
            cost[j].update(g[(j - i) % 3 :: 3])
    dist = [[] for _ in range(3)]
    for i, target in product(list(range(3)), list(range(1, C + 1))):
        cur = sum(D[source][target] * cnt for source, cnt in list(cost[i].items()))
        dist[i].append(cur)
    ans = 1 << 60
    for i, j in product(list(range(C)), repeat=2):
        if i == j:
            continue
        cur = dist[0][i] + dist[1][j]
        cur += min(x for k, x in enumerate(dist[2]) if k not in (i, j))
        ans = min(ans, cur)
    print(ans)


if __name__ == "__main__":
    main()

# Optimized solution
# ABC099D - Good Grid
import sys

readline = sys.stdin.buffer.readline

from collections import Counter
from itertools import product


def main():
    N, C = list(map(int, readline().split()))
    D = [0] + list([0] + list(map(int, readline().split())) for _ in range(C))
    grid = tuple(tuple(map(int, readline().split())) for _ in range(N))
    cost = [Counter() for _ in range(3)]
    for i, g in enumerate(grid):
        for j in range(3):
            cost[j].update(g[(j - i) % 3 :: 3])
    dist = [[] for _ in range(3)]
    for i, tgt in product(list(range(3)), list(range(1, C + 1))):
        cur = sum(D[src][tgt] * cnt for src, cnt in list(cost[i].items()))
        dist[i].append(cur)
    ans = 1 << 60
    for i, j in product(list(range(C)), repeat=2):
        if i == j:
            continue
        cur = dist[0][i] + dist[1][j]
        cur += min(x for k, x in enumerate(dist[2]) if k not in (i, j))
        ans = min(ans, cur)
    print(ans)


if __name__ == "__main__":
    main()
# Original solution
# ABC099D - Good Grid
import sys
input = sys.stdin.readline

from collections import defaultdict
from itertools import product


def main():
    N, C = list(map(int, input().split()))
    D = [0] + list([0] + list(map(int, input().split())) for _ in range(C))
    grid = tuple(tuple(map(int, input().split())) for _ in range(N))
    cost = {i: defaultdict(int) for i in range(3)}
    for i, g in enumerate(grid):
        for j, x in enumerate(g):
            cost[(i + j) % 3][x] += 1
    dist = [[] for _ in range(3)]
    for i, tgt in product(list(range(3)), list(range(1, C + 1))):
        cur = sum(D[src][tgt] * cnt for src, cnt in list(cost[i].items()))
        dist[i].append(cur)
    ans = 1 << 60
    for i, j in product(list(range(C)), repeat=2):
        if i == j:
            continue
        cur = dist[0][i] + dist[1][j]
        cur += min(x for k, x in enumerate(dist[2]) if k not in (i, j))
        ans = min(ans, cur)
    print(ans)


if __name__ == "__main__":
    main()

# Optimized solution
# ABC099D - Good Grid
import sys
input = sys.stdin.readline

from collections import Counter
from itertools import product


def main():
    N, C = list(map(int, input().split()))
    D = [0] + list([0] + list(map(int, input().split())) for _ in range(C))
    grid = tuple(tuple(map(int, input().split())) for _ in range(N))
    cost = [Counter() for _ in range(3)]
    for i, g in enumerate(grid):  # classify each cell by mod3
        for j in range(3):
            cost[(i + j) % 3].update(g[j::3])
    dist = [[] for _ in range(3)]
    # compute the actual cost to change color
    for i, tgt in product(list(range(3)), list(range(1, C + 1))):
        cur = sum(D[src][tgt] * cnt for src, cnt in list(cost[i].items()))
        dist[i].append(cur)
    ans = 1 << 60
    # fix two colors and compute the minimum cost
    for i, j in product(list(range(C)), repeat=2):
        if i == j:
            continue
        cur = dist[0][i] + dist[1][j]
        cur += min(x for k, x in enumerate(dist[2]) if k not in (i, j))
        ans = min(ans, cur)
    print(ans)


if __name__ == "__main__":
    main()
# Original solution
N,C = list(map(int,input().split()))
D = [[int(i) for i in input().split()] for _ in range(C)]
c = [[int(i) for i in input().split()] for _ in range(N)]

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

for i in range(C):
    for j in range(N):
        for k in range(N):
            D_sum[(j+k)%3][i] += D[c[j][k]-1][i]
            
ans = 1000*500*500
for i in range(C):
    for j in range(C):
        for k in range(C):
            if i==j or j==k or k==i:
                continue
            else:
                ans = min(ans, D_sum[0][i]+D_sum[1][j]+D_sum[2][k])
print(ans)      

# Optimized solution
N,C = list(map(int,input().split()))
D = [[int(i) for i in input().split()] for j in range(C)]
c = [[int(i) for i in input().split()] for j in range(N)]

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

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

ans = 1000*500*500
for i in range(C):
    for j in range(C):
        for k in range(C):
            if i==j or j==k or k==i:
                continue
            else:
                ans = min(ans, D_sum[0][i]+D_sum[1][j]+D_sum[2][k])
print(ans)