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

from sys import setrecursionlimit
setrecursionlimit(10000000)
n, q = map(int, input().split())

ct = [0] * (n+1)
o = [0] * (n+1)
g = [[] for _ in range(n+1)]

for i in range(n-1):
  a,b= map(int, input().split())
  g[a].append(b)
  g[b].append(a)

for i in range(q):
  p,x= map(int, input().split())
  o[p] += x

def dfs(p, parent):
  ct[p] += o[p] + ct[parent]
  for i in g[p]:
    if i != parent:
      dfs(i, p)
dfs(1, 0)
print(*ct[1:])


### FIXED CODE ###


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

ct = [0] * (n+1)
o = [0] * (n+1)
g = [[] for _ in range(n+1)]

for i in range(n-1):
  a,b= map(int, input().split())
  g[a].append(b)
  g[b].append(a)

for i in range(q):
  p,x= map(int, input().split())
  o[p] += x

todo = [1]
seen = [False] * (n+1)
while todo:
  p = todo.pop(-1)
  ct[p] += o[p]
  seen[p] = True
  for i in g[p]:
    if seen[i]:
      ct[p] += ct[i]
    else:
      todo.append(i)

print(*ct[1:])
### BUGGY CODE ###

mod=1000000007
N,M=map(int,input().split())
dp=[0]*(N+1)
dp[0]=1
A=[int(input()) for i in range(M)]
for i in range(1,1+N):
    if i in A:
        continue
    else:
        if i==1:
            dp[i]=dp[i-1]%mod
        else:
            dp[i]=(dp[i-1]+dp[i-2])%mod
print(dp[N])

### FIXED CODE ###

mod=1000000007
N,M=map(int,input().split())
dp=[-1]*(N+1)
dp[0]=1

for i in range(M):
    dp[int(input())]=0
for i in range(1,1+N):
    if dp[i]==0:
        continue
    else:
        if i==1:
            dp[i]=dp[i-1]%mod
        else:
            dp[i]=(dp[i-1]+dp[i-2])%mod
if dp[N]==-1:
    print(0)
else:
    print(dp[N])
### BUGGY CODE ###

N, M = map(int, input().split())
ken = [[] for _ in range(N)]
shi = []
for _ in range(M):
    P, Y = map(int, input().split())
    ken[P-1].append(Y)
    shi.append((P, Y))
for k in ken:
    k.sort()
for s1, s2 in shi:
    print("{:06}{:06}".format(s1, ken[s1-1].index(s2)+1))

### FIXED CODE ###

from operator import itemgetter
N, M = map(int, input().split())
iPY = [0]*M
res = [0]*M
for i in range(M):
    P, Y = map(int, input().split())
    iPY[i] = (i, P, Y)
iPY.sort(key=itemgetter(2))
iPY.sort(key=itemgetter(1))
j = 1
p = iPY[0][1]
for i, P, Y in iPY:
    if P != p:
        j = 1
        p = P
    res[i] = "{:06}{:06}".format(P, j)
    j += 1
for s in res:
    print(s)
### BUGGY CODE ###

H, W = map(int,input().split())
# C = [list(input()) for _ in range(H)]
C = []
pre = 0
for i in range(H):
    c = list(input())
    pre += c.count("#")
    C.append(c)

current_list = [(0, 0)]
count = 1
 
while C[H-1][W-1] == '.':
    count += 1
    next_list = []
    for y,x in current_list:
        for i,j in ((1,0),(0,1),):
            if x+j < W and y+i < H:
                if C[y+i][x+j] == '.':
                    C[y+i][x+j] = count
                    next_list.append((y+i,x+j))
    current_list = list(set(next_list))
print(H*W-pre-count)

### FIXED CODE ###

H, W = map(int, input().split())
C = [list(input()) for _ in range(H)]

# bfs 
C[0][0] = 0
pre_list = [(0,0)]
count = 0
 
while C[H-1][W-1] == '.' and len(pre_list) > 0:
    count += 1
    next_list = []
    for y,x in pre_list:
        for i,j in ((1,0),(0,-1),(0,1),(-1,0)):
            if y+i < 0 or x+j < 0 or y+i >= H or x+j >= W:
                continue
            if C[y+i][x+j] == '.':
                C[y+i][x+j] = count
                next_list.append((y+i,x+j))
    pre_list = next_list

if C[H-1][W-1] == '.':
    print(-1)
else:
    black = 0
    for h in C:
        for v in h:
            if v == "#":
                black += 1
    print(H*W-black-count-1)
### BUGGY CODE ###

H,N = map(int,input().split())

magics = [list(map(int,input().split())) for _ in range(N)]
max_A = max(a for a,b in magics)
DP = [float('inf')]*(H+max_A)
DP[0] = 0
for i in range(1,H+max_A):
    DP[i] = min(DP[i-a] + b for a,b in magics)

ans = min(DP[H:])

print(ans)


### FIXED CODE ###

H,N = map(int,input().split())
magics = [list(map(int,input().split())) for _ in range(N)]

max_A = max(a for a,b in magics)
INF = 10**10
DP = [INF]*(H+max_A)
DP[0] = 0

for i in range(1,H+max_A):
    DP[i] = min(DP[i-a] + b for a,b in magics)
    
ans = min(DP[H:])
print(ans)
### BUGGY CODE ###

x,k,d=map(int,input().split())
i=0
while i<k:
    pos=abs(x-d)
    neg=abs(x+d)
    if pos<=neg:
        x=x-d
    elif neg<pos:
        x=x+d
    else:
        break
    i+=1
print(abs(x))

### FIXED CODE ###

x,k,d=map(int,input().split())
x=abs(x)
if x>k*d:
    print(x-k*d)
else:
    if (k-x//d)%2==0:
        print(x-d*(x//d))
    else:
 
        print(abs(d-(x-d*(x//d))))
### BUGGY CODE ###

N = int(input())
A = list(map(int, input().split()))
ans = 0
for i in range(N-1):
    start = i + A[i] + 1
    if start < N:
        for j in range(start, N):
            if abs(i-j) == A[i] + A[j]:
                ans += 1
print(ans)

### FIXED CODE ###

from collections import Counter

N = int(input())
A = list(map(int, input().split()))
i_plus_A = Counter([i + A[i] for i in range(N)])
i_minus_A = [i - A[i] for i in range(N)]
ans = 0
for x in i_minus_A:
    ans += i_plus_A[x]
print(ans)
### BUGGY CODE ###

import sys
import random
sys.setrecursionlimit(10 ** 6)  # 再帰関数の再帰の深さを設定
to_index = lambda x: int(x) - 1  # 入力した数字に1を引いたものを返す
print_list_in_2D = lambda x: print(*x, sep="\n")  # リストの要素を改行を挟んで表示する関数

# 入力を整数に変換して受け取る
def input_int():
    return int(input())

def map_int_input():
    return map(int, input())

MII = map_int_input

def MII_split():
    return map(int, input().split())

def MII_to_index():
    return map(to_index, input())

def MII_split_to_index():
    return map(to_index, input().split())

# 入力全てを整数に変換したものの配列を受け取る
def list_int_inputs():
    return list(map(int, input()))

LII = list_int_inputs

def LII_split():
    return list(map(int, input().split()))

# 2次元リスト化
def LII_2D(rows_number):
    return [LII() for _ in range(rows_number)]

def LII_split_2D(rows_number):
    return [LII_split() for _ in range(rows_number)]

import math
A, B, N = MII_split()

def f(x):
    """最小値を求めたい関数"""
    return math.floor(A * x / B) - A * math.floor(x / B)

def numerical_diff(f, x, h=B):
    """中央差分を元に数値微分する関数"""
    return (f(x + h) - f(x - h)) / (2 * h)

def gradient_descent(f, initial, learning_rate=1, steps=10 ** 5):
    """一階導関数から勾配法で最小値を求める関数"""
    # 現在地を示すカーソル
    x = initial

    # 所定の回数を繰り返す
    for step in range(steps):
        # 現在地の勾配 (どちらにどれだけ進むべきか) を得る
        grad = numerical_diff(f, x)
        x -= learning_rate * grad
        if x < 0:
            x = 0
        elif x > N:
            x = N

    # 最終的な位置を返す
    return f(x)

ma = 0
for _ in range(10 ** 2):
    ini = random.randrange(N + 1)
    tmp = gradient_descent(f, ini)
    # tmp = f(ini)
    if ma < tmp:
        ma = tmp

print(ma)

### FIXED CODE ###

import sys
sys.setrecursionlimit(10 ** 6)  # 再帰関数の再帰の深さを設定
to_index = lambda x: int(x) - 1  # 入力した数字に1を引いたものを返す
print_list_in_2D = lambda x: print(*x, sep="\n")  # リストの要素を改行を挟んで表示する関数

# 入力を整数に変換して受け取る
def input_int():
    return int(input())

def map_int_input():
    return map(int, input())

MII = map_int_input

def MII_split():
    return map(int, input().split())

def MII_to_index():
    return map(to_index, input())

def MII_split_to_index():
    return map(to_index, input().split())

# 入力全てを整数に変換したものの配列を受け取る
def list_int_inputs():
    return list(map(int, input()))

LII = list_int_inputs

def LII_split():
    return list(map(int, input().split()))

# 2次元リスト化
def LII_2D(rows_number):
    return [LII() for _ in range(rows_number)]

def LII_split_2D(rows_number):
    return [LII_split() for _ in range(rows_number)]

import math

A, B, N = MII_split()

def f(x):
    return math.floor(A * x / B) - A * math.floor(x / B)

# max = 0
# for x in range(min(B + 1, N + 1)):
#     if x > N:
#         break
#     fx = f(x)
#     # print(fx)
#     if fx > max:
#         max = fx
print(f(min(B-1, N)))
### BUGGY CODE ###

import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    N, K = [int(x) for x in input().split()]
    P = [int(x) for x in input().split()]
    C = [int(x) for x in input().split()]

    ans = -float("inf")
    for i in range(N):
        next = P[i] - 1
        cnt = 0
        tmp = 0

        f = False
        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if next == i:
                break
            if cnt == K or next == i:
                f = True
                break
            next = P[next] - 1

        if f or tmp <= 0:
            continue

        q, r = divmod(K, cnt)
        next = P[i] - 1
        tmp *= q
        cnt = 0
        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if cnt == r:
                break
            next = P[next] - 1
    print(ans)


if __name__ == '__main__':
    main()


### FIXED CODE ###

import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    N, K = [int(x) for x in input().split()]
    P = [int(x) - 1 for x in input().split()]
    C = [int(x) for x in input().split()]

    ans = max(C)
    for i in range(N):
        next = P[i]
        cnt = 0
        tmp = 0

        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if cnt == K or next == i:
                break
            next = P[next]

        if cnt == K or tmp <= 0:
            continue

        q = K // cnt
        r = K % cnt
        next = P[i]
        if q != 0:
            tmp *= (q - 1)
            q -= 1
            r += cnt
            ans = max(ans, tmp)
        else:
            tmp = 0
        while r > 0:
            tmp += C[next]
            ans = max(ans, tmp)
            next = P[next]
            r -= 1
    print(ans)


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

S = list(input())
N = len(S)
child = [1] * N

# 最初のR
count = 0
for i in range(N):
    count += 1
    if S[i] == "R" and S[i+1] == "L":
        if count % 2 != 0:
            child[0] -= 1
            child[i] += 1
        else:
            child[0] -= 1
            child[i+1] += 1
        break

for i in range(1, N-1):
    if (S[i] == "R" and S[i+1] == "L") or (S[i] == "L" and S[i-1] == "R"):
        continue
    else:
        if S[i] == "R":
            count = 0
            for j in range(i,N):
                count += 1
                if S[j] == "R" and S[j+1] == "L":
                    # 偶数の場合
                    if count % 2 != 0:
                        child[i] -= 1
                        child[j] += 1
                    else:
                        child[i] -= 1
                        child[j+1] += 1
                    break

        elif S[i] == "L":
            count = 0
            for j in reversed(range(i)):
                count += 1
                if S[j] == "L" and S[j-1] == "R":
                    # 偶数の場合
                    if count % 2 == 0:
                        child[i] -= 1
                        child[j] += 1
                    else:
                        child[i] -= 1
                        child[j-1] += 1                        
                    break

# 最後のL
count = 0
for i in reversed(range(N)):
    count += 1
    if S[i] == "L" and S[i-1] == "R":
        if count % 2 != 0:
            child[-1] -= 1
            child[i] += 1
        else:
            child[-1] -= 1
            child[i-1] += 1
        break

ans = [str(n) for n in child]
ans = " ".join(ans)
print(ans)

### FIXED CODE ###

S = list(input())
N = len(S)
child = [1] * N
memo = []

# RLのインデックスを取得する
for i in range(N-1):
    if S[i] == "R" and S[i+1] == "L":
        memo.append(i)
        memo.append(i+1)
memo.append("dummy")
count = 0
for i in range(N):
    if i != memo[count]:
        if S[i] == "R":
            if (memo[count] - i) % 2 == 0:
                child[memo[count]] += 1
                child[i] -= 1
            else:
                child[memo[count+1]] += 1
                child[i] -= 1
        elif S[i] == "L":
            if (i - memo[count-1]) % 2 == 0:
                child[memo[count-1]] += 1
                child[i] -= 1
            else:
                child[memo[count-2]] += 1
                child[i] -= 1
    else:
        count += 1

ans = [str(n) for n in child]
ans = " ".join(ans)
print(ans)
### BUGGY CODE ###

p = 10**7+10
K = int(p**0.5)
P = [1 for _ in range(K)]
P[0]=0
P[1]=0
for i in range(2,int(K**0.5)+1):
    for j in range(i*i,K,i):
        P[j]=0
Q = []
for i in range(2,K):
    if P[i]==1:
        Q.append(i)
def f(x):
    if x==1:
        return 1
    C = {}
    for q in Q:
        k = 0
        while x%q==0:
            x = x//q
            k += 1
        if k>0:
            C[q]=k
        if x==1:break
    if x>1:
        C[x] = 1
    res = 1
    for y in C:
        res = res*(C[y]+1)
    return res
N = int(input())
tot = 0
for i in range(1,N+1):
    tot += i*f(i)
print(tot)

### FIXED CODE ###

N = int(input())
ans = 0
for i in range(1,N+1):
    for j in range(i,N+1,i):
        ans += j
print(ans)
### BUGGY CODE ###

from scipy.sparse import csc_matrix
import sys
input = sys.stdin.readline

N = int(input())
ABC = [[int(x) for x in input().split()] for _ in range(N-1)]
row,col,val = zip(*ABC)

edge = csc_matrix((val,(row,col)),(N+1,N+1))

Q,K = map(int,input().split())
 
from scipy.sparse.csgraph import dijkstra
dist = dijkstra(edge,directed = False, indices = K).astype(int)
 
for _ in range(Q):
  x,y = map(int,input().split())
  print(dist[x] + dist[y])


### FIXED CODE ###

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)

N = int(input())
edge = [[] for _ in range(N+1)]
 
for _ in range(N-1):
  a,b,c = map(int,input().split())
  edge[a].append((b,c))
  edge[b].append((a,c))

Q,K = map(int,input().split())

dist = [None]*(N+1)

def set_dist(x,d):
  dist[x] = d
  for y,dd in edge[x]:
    if dist[y] is not None:
      continue
    set_dist(y,d+dd)

set_dist(K,0)

for _ in range(Q):
  x,y = map(int,input().split())
  print(dist[x] + dist[y])
### BUGGY CODE ###

#python3
#python3
import numpy as np
n=int(input())
a=np.array([int(i) for i in input().split()])
MOD = int(1e9+7)
ans=0
for k in range(60):
  x=0
  for i in range(n):
    if(a[i]>>k)&1:
      x+=1
  c=x*(n-x)*2**k
  ans+=c
print(ans%MOD)


### FIXED CODE ###

#python3
import numpy as np
N = int(input())
A = np.array([int(_) for _ in input().split()])
mod = 10**9 + 7
ans = 0
for b in range(60):
    B = (A >> b) & 1
    M = np.count_nonzero(B)
    ans += 2**b * M * (N - M)
    ans %= mod
print(ans)
### BUGGY CODE ###

H=int(input())
import copy
List=[]
while True:
    H=H+1
    if H%2==0:
        List.append(H)
        l=copy.deepcopy(List)
        h=l[0]
        while h%2==0:
            h=h/2
            if h==1:
                print(H-1)
                exit()
            else:
                List.clear()
                l.clear()
    else:
        pass

### FIXED CODE ###

H=int(input())
def f(n):
    if n==1:
        return 1
    else:
        return 1+f(n//2)*2
print(f(H))
### BUGGY CODE ###

import sys


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

def main():
    n, k = map(int, input().split())
    if k == 1:
        n = 0
        print(n)
        return
    while n > k//2:
        n = abs(n-k)
    print(n)

main()

### FIXED CODE ###

import sys


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

def main():
    n, k = map(int, input().split())
    a = n % k
    print(min(a, k-a))

main()
### BUGGY CODE ###

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

tmp = 1
for i in range(k):
  tmp *= a[k-1-i]

for i in range(k, n):
  total = 1
  for j in range(k):
    total *= a[i-j]
  if total > tmp:
    print('Yes')
  else:
    print('No')
  tmp = total
  

### FIXED CODE ###

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

for i in range(k, n):
  if a[i] > a[i - k]:
    print('Yes')
  else:
    print('No')
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10**6)


def solve(c, idx, N, S, ans):
    if len(c)==3:
        ans.add(c)
        return
    if idx >= len(S):
        return
    solve(c+S[idx], idx+1, N, S, ans)
    solve(c, idx+1, N, S, ans)

if __name__ == "__main__":
    N = int(input())
    S = input()
    ans = set()
    solve("", 0, N, S, ans)
    print(len(ans))

### FIXED CODE ###

N = int(input())
S = input()
ans = 0
for i in range(1000):
    cnt = 0
    n = str(i).zfill(3)
    for c in S:
        if c == n[cnt]:
            cnt += 1

        if cnt == 3:
            ans += 1
            break

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

N=int(input().split(" ")[0])
A=input().split(" ")
x=[]
for i in range(N):
    k=i+1
    y=0
    while k<=N-1:
        if y< int(A[k])-int(A[i]):
            y=int(A[k])-int(A[i])
        k+=1
    if y!=0:    
        x.append(y)


print(x.count(max(x)))


### FIXED CODE ###

nt=input().split(" ")
N=int(nt[0])
T=int(nt[1])


a=input().split(" ")
int_a=[]
maxlist=[]
for i in range(N):
    int_a.append(int(a[i]))

reva=int_a
reva.reverse()
max=0
for i in range(N):
    if reva[i]>max:
        max=reva[i]
    maxlist.append(max)

maxlist.reverse()
int_a.reverse()


max=0
count=1
for i in range(N):
    if maxlist[i]-int_a[i]>max:
        count=1
        max=maxlist[i]-int_a[i]
    elif maxlist[i]-int_a[i]==max:
        count+=1

print(count)
### BUGGY CODE ###

import heapq
N , M = map(int ,input().split())
a = list(map(int ,input().split()))

heapq.heapify(a)

for i in range(M):
    b , c = map(int ,input().split())
    for _ in range(b):
        if c <= a[0]:
            break
        heapq.heappop(a)
        heapq.heappush(a,c)
print(sum(a))

### FIXED CODE ###

import heapq
N , M = map(int ,input().split())
a = list(map(int ,input().split()))

heapq.heapify(a)
lst = []
for i in range(M):
    b , c = map(int ,input().split())
    lst.append([b, c])
lst.sort(reverse = True , key = lambda x: x[1])
#print(lst)
for i in range(M):
    for _ in range(lst[i][0]):
        if lst[i][1] <= a[0]:
            break
        heapq.heappop(a)
        heapq.heappush(a,lst[i][1])
print(sum(a))
### BUGGY CODE ###

a,b,c,d=map(int,input().split())
for i in range(b+1):
  if c*i>=a:
    clst=[c*i for i in range(i,(b-c*i)//c+i+1)]
    break
for i in range(b+1):
  if d*i>=a:
    dlst=[d*i for i in range(i,(b-d*i)//d+i+1)]
    break
lst=set(clst+dlst)
print(b-a+1-len(lst))
  


### FIXED CODE ###

a,b,c,d=map(int,input().split())
if d>c:
  euclid2,euclid1=c,d
  e1,e2=euclid1,euclid2
  while not euclid2==0:
    euclid1=euclid1%euclid2
    euclid1,euclid2=euclid2,euclid1
    cd=c*d//euclid1
else:
  euclid2,euclid1=d,c
  e1,e2=euclid1,euclid2
  while not euclid2==0:
    euclid1=euclid1%euclid2
    euclid1,euclid2=euclid2,euclid1
    cd=c*d//euclid1
  
c1=(a-1)//c+1
c2=(b-c1*c)//c+1
d1=(a-1)//d+1
d2=(b-d1*d)//d+1
cd1=(a-1)//cd+1
cd2=(b-cd1*cd)//cd+1  
print(b-a+1-c2-d2+cd2)
### BUGGY CODE ###

k,s = map(int,input().split())

d = {}
for x in range(k+1):
    mx_y = min(s-x,k)
    for y in range(mx_y+1):
        z = s - x - y
        if(z >= 0 and z <= k):
            key = (x,y,z)
            d[key] = 1

print(len(d))



### FIXED CODE ###

k,s = map(int,input().split())

d = {}
cnt = 0
for x in range(k+1):
    for y in range(x+1):
        z = s - x - y
        if(z >= 0 and z <= y):
            if(x == y and y == z):
                cnt += 1
            elif(x == y or y == z or z == x):
                cnt += 3
            else:
                cnt += 6

print(cnt)
### BUGGY CODE ###

import sys
from collections import deque
h,w = map(int,input().split())
sx,sy = map(int,input().split())
sx -= 1
sy -= 1
gx,gy = map(int,input().split())
gx -= 1
gy -= 1
route = []
for i in range(h):
  lst = list(input())
  route.append(lst)
  
brock = [['#']*w for i in range(h)]
s = 0
que = deque([])
dx = [-1,0,1,0]
dy = [0,-1,0,1]

brock[sx][sy] = 0
que.append((sx,sy))



while que:
  
  (p,q) = que.popleft()
  if (p,q) == (gx,gy):
    print(brock[gx][gy])
    sys.exit()
  for i in range(4):
    p2,q2 = p+dx[i],q+dy[i]
    if 0 <= p2 < h and 0<= q2 < w and route[p2][q2] == '.' and brock[p2][q2] == '#':
      brock[p2][q2] = brock[p][q]
      que.append((p2,q2))
      
  
  if len(que) == 0:
    
    s += 1
    for u in range(h):
      for v in range(w):
        if brock[u][v] == s-1:
          x,y = u,v
          for j in range(-2,3):
             for k in range(-2,3):
                x2 = x+j
                y2 = y+k
                if 0 <= x2 < h and 0<= y2 < w and route[x2][y2] == '.' and brock[x2][y2] == '#':
                  brock[x2][y2] = s
                  que.append((x2,y2))
            
                  
              
print(-1)              
            



### FIXED CODE ###

import sys
from collections import deque
h,w = map(int,input().split())
sx,sy = map(int,input().split())
sx -= 1
sy -= 1
gx,gy = map(int,input().split())
gx -= 1
gy -= 1
route = []
for i in range(h):
  lst = list(input())
  route.append(lst)
  
brock = [['#']*w for i in range(h)]

que = deque([])
dx = [-1,0,1,0]
dy = [0,-1,0,1]

brock[sx][sy] = 0
que.append((sx,sy))



while que:
  
  (p,q) = que.popleft()
  if (p,q) == (gx,gy):
    print(brock[gx][gy])
    sys.exit()
  for i in range(4):
    p2,q2 = p+dx[i],q+dy[i]
    if 0 <= p2 < h and 0<= q2 < w and route[p2][q2] == '.' and (brock[p2][q2] == '#' or brock[p2][q2] > brock[p][q]):
      brock[p2][q2] = brock[p][q]
      que.appendleft((p2,q2))
  
  for j in range(-2,3):
    for k in range(-2,3):
      p3 = p+j
      q3 = q+k
      if 0 <= p3 < h and 0<= q3 < w and route[p3][q3] == '.' and brock[p3][q3] == '#':
        brock[p3][q3] = brock[p][q]+1
        que.append((p3,q3))
        
        
            
                  
              
print(-1)
### BUGGY CODE ###

# 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(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)

### FIXED CODE ###

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