Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

MOD = 10 ** 9 + 7

N, M = map(int, input().split())
S = list(map(int, input().split()))
T = list(map(int, input().split()))

dp = [[1] * (M+1) for _ in range(N+1)]

for i, s in enumerate(S):
    for j, t in enumerate(T):
        dp[i+1][j+1] = dp[i+1][j] + dp[i][j+1]
        if s != t:
            dp[i+1][j+1] -= dp[i][j]
        dp[i+1][j+1] %= MOD

print(dp[N][M])


### FIXED CODE ###

MOD = 10 ** 9 + 7

N, M = map(int, input().split())
S = list(map(int, input().split()))
T = list(map(int, input().split()))

dp = [[1] * (M+1) for _ in range(N+1)]

for i, s in enumerate(S):
    for j, t in enumerate(T):
        dp[i+1][j+1] = dp[i+1][j] + dp[i][j+1]
        if s != t:
            dp[i+1][j+1] -= dp[i][j]
        dp[i+1][j+1] %= MOD

print(dp[N][M])
### BUGGY CODE ###

import math

def main():
    N = int(input())
    Al = [int(x) for x in input().split()]
    center = int(N/2)
    cnt = 0
    for i in range(N):
        for j in range(i,N):
            if i+Al[i] == j-Al[j]:
                cnt += 1
    print(cnt)

if __name__ == '__main__':
    main()


### FIXED CODE ###

import math
from collections import defaultdict

def main():
    N = int(input())
    Al = [int(x) for x in input().split()]
    center = int(N/2)
    cnt = 0
    m = defaultdict(int)
    for i in range(N):
        m[i+Al[i]] += 1
        cnt += m[i-Al[i]]
    print(cnt)

if __name__ == '__main__':
    main()
### BUGGY CODE ###

from bisect import bisect_right, bisect_left

N, M, *A = map(int, open(0).read().split())
A.sort()


def calc(t):
    cnt = 0
    for ai in A:
        cnt += N - bisect_left(A, t - ai)
    if M <= cnt:
        return True
    else:
        return False


def solve():
    left, right = 0, 2 * 10 ** 5 + 1
    while 1 < right - left:
        mid = (left + right) // 2
        if calc(mid):
            left = mid
        else:
            right = mid
    
    ans = 0
    add_cnt = 0
    for ai in A:
        index = bisect_left(A, left - ai)
        add_cnt += N - index
        for aj in A[index:]:
            ans += ai + aj
    ans -= left * (add_cnt - M)
    print(ans)


if __name__ == '__main__':
    solve()


### FIXED CODE ###

from bisect import bisect_left

N, M, *A = map(int, open(0).read().split())
A.sort()


def calc(t):
    cnt = 0
    for ai in A:
        cnt += N - bisect_left(A, t - ai)
    if M <= cnt:
        return True
    else:
        return False


def solve():
    left, right = 0, 2 * 10 ** 5 + 1
    while 1 < right - left:
        mid = (left + right) // 2
        if calc(mid):
            left = mid
        else:
            right = mid
    
    sum_A = [0] * N
    sum_A[-1] = A[-1]
    for i in range(N - 2, -1, -1):
        sum_A[i] = sum_A[i + 1] + A[i]
    
    ans = 0
    add_cnt = 0
    for ai in A:
        index = bisect_left(A, left - ai)
        if index == N:
            continue
        add_cnt += N - index
        ans += (N - index) * ai + sum_A[index]
    ans -= left * (add_cnt - M)
    print(ans)


if __name__ == '__main__':
    solve()
### BUGGY CODE ###

# -*- coding: utf-8 -*-
def store_lamp(g, j, v):
    while j >= 0:
        if g[j] is not None:
            break
        g[j] = v
        j -= 1


def store_lamp_h(g, i, j, v):
    while i >= 0:
        if g[i][j] is not None:
            break
        g[i][j] = v
        i -= 1

h, w = map(int, input().split())
s = []

hg = [[None] * w for _ in range(h)]
wg = [[None] * w for _ in range(h)]

for _ in range(h):
    s.append(input())

for i in range(h):
    pre = 0
    for j in range(w):
        if s[i][j] == '#':
            hg[i][j] = 0
            if pre != 0:
                store_lamp(hg[i], j-1, pre)
            pre = 0
        else:
            pre += 1

    if pre != 0:
        store_lamp(hg[i], w-1, pre)

for j in range(w):
    pre = 0
    for i in range(h):
        if s[i][j] == '#':
            wg[i][j] = 0
            if pre != 0:
                store_lamp_h(wg, i-1, j, pre)
            pre = 0
        else:
            pre += 1

    if pre != 0:
        store_lamp_h(wg, h-1, j, pre)

l = 0
for hh, wh in zip(hg, wg):
    for hw, ww in zip(hh, wh):
        l = max(l, hw+ww)

print(l-1)


### FIXED CODE ###

# -*- coding: utf-8 -*-
def store_lamp(g, j, v):
    while j >= 0:
        if g[j] is not None:
            break
        g[j] = v
        j -= 1


def store_lamp_h(g, i, j, v):
    while i >= 0:
        if g[i][j] is not None:
            break
        g[i][j] = v
        i -= 1

h, w = map(int, input().split())
s = []

hg = [[None] * w for _ in range(h)]
wg = [[None] * w for _ in range(h)]

for _ in range(h):
    s.append(input())

for i in range(h):
    pre = 0
    for j in range(w):
        if s[i][j] == '#':
            hg[i][j] = 0
            if pre != 0:
                store_lamp(hg[i], j-1, pre)
            pre = 0
        else:
            pre += 1

    if pre != 0:
        store_lamp(hg[i], w-1, pre)

for j in range(w):
    pre = 0
    for i in range(h):
        if s[i][j] == '#':
            wg[i][j] = 0
            if pre != 0:
                store_lamp_h(wg, i-1, j, pre)
            pre = 0
        else:
            pre += 1

    if pre != 0:
        store_lamp_h(wg, h-1, j, pre)

l = 0
for hh, wh in zip(hg, wg):
    for hw, ww in zip(hh, wh):
        l = max(l, hw+ww)

print(l-1)
### BUGGY CODE ###

def main():
    D, N = list(map(int, input().split()))
    mod = 100 ** D
    cnt = 0
    i = 1
    while True:
        if i % 100 == 0:
            continue
        if i % mod == 0:
            cnt += 1
        if cnt == N:
            print(i)
            break
        i += 1


if __name__ == "__main__":
    main()


### FIXED CODE ###

D, N = map(int, input().split())
if N < 100:
    print(N * (100**D))
else:
    print(101 * (100**D))
### BUGGY CODE ###

N, Q = map(int, input().split())
S = input()

for i in range(Q):
    L, R = map(int, input().split())
    print(S[L-1:R].count("AC"))

### FIXED CODE ###

N, Q = map(int, input().split())
S = input()
lr_list = [list(map(int, input().split())) for i in range(Q)]
ac_sum = [0]
count = 0
for i, char in enumerate(S):
    if i != 0:
        if char == "C" and buf == "A":
            count += 1
    ac_sum.append(count)
    buf = char

for lr in lr_list:
    print(ac_sum[lr[1]] - ac_sum[lr[0]])
### BUGGY CODE ###

X = int(input())

K=1
y=X
while y != 0:
  K+=1
  y+=X
#
print(k)



### FIXED CODE ###

X = int(input())

K=1
y=X % 360
while y != 0:
  K+=1
  y=(y+X)% 360
#
print(K)
### BUGGY CODE ###

a,b = map(int,input().split())
l = [i for i in range(a,b+1)]
ans = 0
for i in range(len(l)):
    ans ^= l[i]
print(ans)

### FIXED CODE ###

a,b = map(int,input().split())
def func(x):
    if x%2 == 1:
        ans = ((x//2) + 1)%2
        return ans
    else:
        tmp = (x//2)%2
        ans = tmp^x
        return ans

print(func(a-1)^func(b))
### BUGGY CODE ###

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

for i in range(1,N+1):
    print(A.count(i))



### FIXED CODE ###


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

A.sort()
if A[0]==0:
    A.remove(0)

l=len(A)
k=0

ans=1

m=max(A)

for i in range(l-1):
    if A[i+1]>A[i]:
        k=A[i]
        print(ans)
        while A[i+1]!=k+1:
            k=k+1
            print(0)
        ans=1
    else:
        ans=ans+1
if A[l-1]==A[l-2]:
    print(ans)
else:
    print(ans)
    
   
for j in range(m+1,N+1):
    print(0)
### BUGGY CODE ###

N, M = map(int, input().split())
input_list = [[int(i) for i in input().split()] for i in range(M)]
first_element = []
second_element = []

for element in input_list:
    if element[0] == 1:
        first_element.append(element[1])
    elif element[1] == N:
        second_element.append(element[0])

for i in first_element:
    if i in second_element:
        print("POSSIBLE")
        break
else:
    print("IMPOSSIBLE")

### FIXED CODE ###

N, M = map(int, input().split())
input_list = [[int(i) for i in input().split()] for i in range(M)]

first_element = set()
second_element = set()

for element in input_list:
    if element[0] == 1:
        first_element.add(element[1])
    elif element[1] == N:
        second_element.add(element[0])

if first_element & second_element:
    print("POSSIBLE")
else:
    print("IMPOSSIBLE")
### BUGGY CODE ###

#C
n = int(input())
a = list(map(int,input().split()))

ans = [0 for _ in range(n)]
for i in range(1,n+1):
    tmp = a.index(i)
    ans[i-1] = (tmp+1)
    
print(*ans)
    

### FIXED CODE ###

n = int(input())
a = list(map(int,input().split()))

ans = [0 for _ in range(n)]

for i in range(n):
    ans[a[i] - 1] = i + 1
print(*ans)
### BUGGY CODE ###

import re

NQ = [int(i) for i in input().split()]
N = NQ[0]
Q = NQ[1]
S = input()
check = [0] * (N - 1)
answer = []
for i in range(N - 1):
    check[i] = 1 if S[i:i + 2] == "AC" else 0


for j in range(Q):
    lr = [int(i) for i in input().split()]
    answer.append(sum(check[lr[0] - 1:lr[1] - 1]))

for s in answer:
    print(s)

### FIXED CODE ###

import re

NQ = [int(i) for i in input().split()]
N = NQ[0]
Q = NQ[1]
S = input()
LR = [[int(i) for i in input().split()] for j in range(Q)]
check = [0] * N
for i in range(N - 1):
    check[i + 1] = check[i] + (1 if S[i:i + 2] == "AC" else 0)


for j in range(Q):
    print((check[LR[j][1] - 1]) - (check[LR[j][0] - 1]))
### BUGGY CODE ###

def resolve():
    # 整数 1 つ
    # n = int(input())
    # 整数複数個
    n, k = list(map(int, input().split()))
    # 整数 N 個 (改行区切り)
    # N = [int(input()) for i in range(N)]
    # 整数 N 個 (スペース区切り)
    A = list(map(int, input().split()))
    # 整数 (縦 H 横 W の行列)
    # A = [list(map(int, input().split())) for i in range(H)]

    Unique = list(set(A))
    Dic = {x:A.count(x) for x in set(A)}

    if len(set(A)) <= k:
        print(0)
    else:
        cnt = 0
        for i in range(len(set(A)) - k):
            cnt += min(Dic.values())
            del Dic[min(Dic, key=Dic.get)]
        print(cnt)
resolve()

### FIXED CODE ###

N,K = map(int,input().split())
A = list(map(int,input().split()))

Ad = {x:0 for x in set(A)}
if len(set(A)) <= K:
    print(0)
else:
    count = 0
    for a in A:
        Ad[a] += 1
    Ad = sorted(Ad.items(), key=lambda x:x[1])
    for i in range(len(set(A))-K):
        count += Ad[i][1]
    print(count)
### BUGGY CODE ###

import sys
a = sys.stdin.readline()
A = int(a)
P = 1
I = 1 
W = 10 ** 9 + 7
while I <= A:
    P *= I
    I += 1
P %= W
print(P)

### FIXED CODE ###

import sys
a = sys.stdin.readline()
A = int(a)
P = 1
I = 1 
W = 10 ** 9 + 7
while I <= A:
    P *= I
    I += 1
    P %= W
print(P)
### BUGGY CODE ###

N,K=map(int,input().split())
A=list(map(int,input().split()))
As=list(set(A))
sa=max(0,len(As)-K)
if sa==0:
    print(0)
    exit
else:
    count=[]
    for i in As:
        count.append(A.count(i))
    num=sorted(count)
    ans=0
    for i in range(sa):
        ans+=num[i]
    print(ans)

### FIXED CODE ###

N,K=map(int,input().split())
A=list(map(int,input().split()))
sa=len(set(A))-K
if sa>0:
    As={}
    for i in range(N):
        if A[i] in As:
            As[A[i]]+=1
        else:
            As[A[i]]=1
    Ass=sorted(As.values())
    print(sum(Ass[:sa]))
else:
    print(0)
### BUGGY CODE ###

S = input()
K = int(input())

ans = []
table ={}

for i in range(len(S)):
    for j in range(len(S)+1):
        if (j-i)>=6:
            break
        if i==j:
            s = S[i]
            if s in table:
                continue
            table[s] = 1
            ans.append(s)
            continue
        if S[i:j]=="":
            continue
        s = S[i:j]
        if s in table:
            continue
        table[s] = 1
        ans.append(s)

ans = sorted(ans)
print(ans[K-1])


### FIXED CODE ###

S = input()
K = int(input())

ans = []
table ={}

for i in range(len(S)):
    for j in range(6):
        if i==j:
            s = S[i]
            if s in table:
                continue
            table[s] = 1
            ans.append(s)
            continue
        if S[i:i+j]=="":
            continue
        s = S[i:i+j]
        if s in table:
            continue
        table[s] = 1
        ans.append(s)

ans = sorted(ans)
print(ans[K-1])
### BUGGY CODE ###

n=int(input())
x=int(input(),2)

for i in range(n-1,-1,-1):
    xi=x^(1<<i)
#    print(xi,popcount(xi),xi%popcount(xi))
    icnt=0
    while xi>0:
        icnt+=1
        xi=xi%bin(xi).count("1")
    print(icnt)        
        

### FIXED CODE ###

import sys
def input(): return sys.stdin.readline().strip()

n=int(input())
xs=input()
xj=xs.count("1")

x=int(xs,2)
xip=x%(xj+1)
if xj!=1:
    xim=x%(xj-1)

for i in range(n-1,-1,-1):
    if xs[n-1-i]=="0":
        pxi=xj+1
        i2=pow(2,i,pxi)
        xi=(xip+i2)%pxi
    elif xj==1:
        print(0)
        continue
    else:
        pxi=xj-1
        i2=pow(2,i,pxi)
        xi=(xim-i2)%pxi
    xi=xi%pxi
    if xi==0:
        print(1)
        continue
    icnt=1
    while xi>0:
#        print("i",i,"xi",xi,"icnt",icnt)
        icnt+=1
        xi=xi%(bin(xi).count("1"))
    print(icnt)
### BUGGY CODE ###

S = input()

ans = []
for left in range(len(S)):
    for right in range(left + 5, len(S) + 1):
        temp = int(S[left:right])
        if temp % 2019 == 0:
            ans.append([left, right])

print(len(ans))


### FIXED CODE ###

S = input()
N = len(S)

map_ = [-1] * 2019
map_[0] = 0
ans = 0
now = 0
for i in range(0, N):
    now = (now + int(S[N - i - 1]) * pow(10, i, 2019)) % 2019
    map_[now] += 1
    ans += map_[now]

print(ans)
### BUGGY CODE ###

n = int(input())
p = list(map(int,input().split()))
cnt = 0
for i in range(n):
    judge = 0
    for j in range(i):
        if p[i] > p[j]:
            judge=1
            break
        else:
            pass
    if judge == 0:    
        cnt += 1
print(cnt)

### FIXED CODE ###

n = int(input())
p = list(map(int,input().split()))
cnt = 0
min = p[0]
for i in range(n):
    if p[i] <= min:
        min = p[i]
        cnt += 1
    else:
        pass
print(cnt)
### BUGGY CODE ###

# -*- coding: utf-8 -*-

N = int(input())

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

for x in range(1, N + 1):
    print(A.index(x) + 1, end=' ')


### FIXED CODE ###

# -*- coding: utf-8 -*-

N = int(input())

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

B = [0 for _ in range(N)]
i = 1

for x in A:
    B[x - 1] = i
    i += 1

print(' '.join(map(str, B)))
### BUGGY CODE ###

N = int(input())
L = sorted(list(map(int,input().split())),reverse = False)
cnt = 0
for a in range(0,N-2):
    A = L[a]
    for b in range(a+1,N-1):
        B = L[b]
        low = b+1
        high = N-1
        while(low+1 != high and low != high):
            mid = (low+high)//2
            if(A+B > L[mid]):
                low = mid
            else:
                high = mid
        if(A+B > L[high]):
            cnt += high-b
        elif(A+B > L[low]):
            cnt += low-b
print(cnt)      

### FIXED CODE ###

from bisect import bisect_left
N = int(input())
L = sorted(list(map(int,input().split())),reverse = False)
cnt = 0
for a in range(0,N-2):
    A = L[a]
    for b in range(a+1,N-1):
        B = L[b]
        cnt += bisect_left(L,A+B)-b-1
print(cnt)
### BUGGY CODE ###

#ver.2 再帰メモ化
INF=1000100
dp=[INF]*(100010)
h=[0]*(100010)
n=int(input())
x=list(map(int,input().split()))
for i in range(n):
    h.insert(i,x[i])

def rec(i):
    if dp[i]<INF:return dp[i]

    if i==0:return 0

    res=INF
    res=min(res,rec(i-1)+abs(h[i]-h[i-1]))
    if i>1:res=min(res,rec(i-2)+abs(h[i]-h[i-2]))
    dp[i]=res
    return dp[i]

print(rec(n-1))

### FIXED CODE ###

n=int(input())
h=list(map(int,input().split()))
dp=[1000000000]*(n)
dp[0]=0
dp[1]=abs(h[1]-h[0])
for i in range(2,n):
    dp[i]=min(dp[i-1]+abs(h[i-1]-h[i]),dp[i-2]+abs(h[i-2]-h[i]))
print(dp[n-1])
### BUGGY CODE ###

N = int(input())
A = [input() for i in range(N)]

prev = []
next = 0
count = 0
while(next not in prev):
    prev.append(next)
    next = int(A[next])-1
    count += 1
    if(next == 1):
        print(count)
        break
else:
    print(-1)


### FIXED CODE ###

N = int(input())
A = [input() for i in range(N)]

prev = []
next = 0
count = 0
while(count < N):
    next = int(A[next])-1
    count += 1
    if(next == 1):
        print(count)
        break
else:
    print(-1)
### BUGGY CODE ###

N = int(input())

ans = 0

for i in range(1, N + 1):
    if i == N:
        continue
    else:
        ans += i % (i+1)
print(ans)


### FIXED CODE ###

N = int(input())

print(N*(N+1)//2-N)
### BUGGY CODE ###

n = int(input())
s = input()
ans = n
for i in range(n):
    if i == 0:
        nin = s[1:n].count("E")
    elif i == n - 1:
        nin = s[0:n-1].count("W")
    else:
        nin = s[0:i].count("W") + s[i+1:n].count("E")
    if nin < ans:
        ans = nin
print(ans)

### FIXED CODE ###

n = int(input())
s = input()
nin = s[1:n].count("E")
ans = nin
for i in range(n - 1):
    if s[i] == "E" and s[i + 1] == "E":
        nin -= 1
    elif s[i] == "W" and s[i + 1] == "W":
        nin += 1
    if nin < ans:
        ans = nin
print(ans)
### BUGGY CODE ###

import bisect
import numpy as np

def search(l, val):
    a = bisect.bisect_left(l, val)
    b = bisect.bisect_right(l, val)
    return list(range(a, b))

def resolve():
    N = int(input())
    X = [list(map(int,input().split())) for _ in range(N-1)]
    # u番目の頂点, v番目の頂点, 距離w
    
    X0 = sorted(X, key=lambda x: x[1])
    X1 = sorted(X)
    X0np = np.array(X0)
    X1np = np.array(X1)

    # 未彩色は-1
    color = [-1] * N
    color[0] = 0

    q = [(1, color[0])]
    while len(q) > 0:
        q0 = q[0]
        q = q[1:]

        r0 = search(X0np[:, 1], q0[0])
        for r in r0:
            val = X0[r][0]
            if color[val-1] == -1:
                c = (q0[1] + X0[r][2]) % 2
                color[val-1] = c
                q.append((val, c))
        r1 = search(X1np[:, 0], q0[0])
        for r in r1:
            val = X1[r][1]
            if color[val-1] == -1:
                c = (q0[1] + X1[r][2]) % 2
                color[val-1] = c
                q.append((val, c))
    
    for c in color:
        print(c)
        
resolve()

### FIXED CODE ###

from queue import Queue

N = int(input())
X = [list(map(int, input().split())) for _ in range(N-1)]
X = list(map(lambda x: (x[0]-1, x[1]-1, x[2]), X))
# [u番目の頂点, v番目の頂点, 距離w]
# インデックスは0,...,N-1

# 頂点iの隣接情報を保持
node = [[] for i in range(N)]
for x in X:
    u, v, w = x
    node[u].append((v, w))
    node[v].append((u, w))

# 頂点iの色, 未彩色は-1
color = [-1] * N

# 幅優先探索で全頂点の色を決定
# 頂点0の色を0とする
q = Queue()
color[0] = 0
q.put((0, color[0]))
while not q.empty():
    q0 = q.get()

    n = q0[0]
    c = q0[1]
    neighbors = node[n]
    for p in neighbors:
        if color[p[0]] == -1:
            color[p[0]] = (c + p[1]) % 2
            q.put((p[0], color[p[0]]))

for c in color:
    print(c)
### BUGGY CODE ###

K = int(input())

cnt_dig = 1
sev = 7
if K % 2 == 0:
    print(-1)
else:
    while 1 :
        if sev % K == 0:
            print(cnt_dig)
            break
        else:
            sev *= 10
            sev += 7
            cnt_dig += 1

### FIXED CODE ###

import sys

K = int(input())
a = []
i = 1

a.append(7 % K)
while i < K:
    a.append((a[i-1]*10+7) % K)
    i += 1

i = 0
while i < K:
    if(a[i]==0):
        print(i+1)
        exit(0)
    i += 1

print(-1)
### BUGGY CODE ###

def slove():
    import sys
    input = sys.stdin.readline
    n = int(input().rstrip('\n'))
    a = [list(map(int, input().rstrip('\n').split())) for _ in range(n)]
    ls = [0] * n
    mt = [0] * n
    cnt = 0
    for i in range(10 ** 15):
        cnt += 1
        f = [False] * n
        for i in range(n):
            if ls[i] != -1:
                mt[i] = a[i][ls[i]]
        for i in range(n):
            if not f[i]:
                if ls[i] != -1:
                    if i + 1 == mt[mt[i]-1]:
                        f[i] = True
                        f[mt[i]-1] = True
        bb = False
        for i in range(n):
            if f[i]:
                if ls[i] + 1 < n - 1:
                    ls[i] += 1
                    bb = True
                else:
                    ls[i] = -1
        b = True
        for i in range(n):
            if ls[i] != -1:
                b = False
                break
        if b:
            print(cnt)
            exit()
        if not bb:
            print(-1)
            exit()


if __name__ == '__main__':
    slove()


### FIXED CODE ###

def slove():
    import sys
    import collections
    input = sys.stdin.readline
    n = int(input().rstrip('\n'))
    a = [list(map(int, input().rstrip('\n').split())) for _ in range(n)]
    ad = [0] * n
    dq = collections.deque([[0, i + 1] for i in range(n)])
    for i in range(10 ** 15):
        fd = {}
        while True:
            if len(dq) != 0:
                d, q = dq.popleft()
                q -= 1
                if d <= i:
                    if ad[q] < n - 1:
                        qq = a[q][ad[q]] - 1
                        tq = a[qq][ad[qq]] - 1
                        if q == tq and qq not in fd and tq not in fd:
                            ad[qq] += 1
                            ad[tq] += 1
                            if ad[qq] < n - 1:
                                dq.append([d + 1, qq + 1])
                            if ad[tq] < n - 1:
                                dq.append([d + 1, tq + 1])
                            fd[qq] = 0
                            fd[tq] = 0
                else:
                    dq.append([d, q + 1])
                    break
            else:
                break
        if len(dq) == 0:
            b = True
            for v in ad:
                if v != n - 1:
                    b = False
                    break
            if b:
                print(i + 1)
                exit()
            else:
                print(-1)
                exit()


if __name__ == '__main__':
    slove()
### BUGGY 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 a in range(c**2):
        for k in range(c):
            i,j=a//c,a%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()


### FIXED 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)]
    x0,x1,x2={},{},{}
    for p in range(n**2):
        h,w=p//n,p%n
        x=(h+w)%3
        o=t[h][w]-1
        if x==0:
            if o in x0: x0[o]+=1
            else: x0[o]=1
        if x==1:
            if o in x1: x1[o]+=1
            else: x1[o]=1
        if x==2:
            if o in x2: x2[o]+=1
            else: x2[o]=1
    ans=-1
    for a in range(c**2):
        for k in range(c):
            i,j=a//c,a%c
            q=[i,j,k]
            if len(set(q))<3: continue
            chk=0
            for p in x0:
                chk+=d[p][q[0]]*x0[p]
            for p in x1:
                chk+=d[p][q[1]]*x1[p]
            for p in x2:
                chk+=d[p][q[2]]*x2[p]
            if ans==-1: ans=chk
            ans=min(ans,chk)

    print(ans)

if __name__=="__main__":
    sol()