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

import numpy as np
import sys

N = int(sys.stdin.readline())
A = np.array(sorted(map(int, sys.stdin.readline().split(' '))))

dp = np.ones(N, dtype=np.bool)

for i in range(N - 1):
    if not dp[i]:
        continue
    if not np.any(dp[i:]):
        break
    dp[i + 1:] &= (A[i + 1:] % A[i] != 0)
    dp[i] &= (A[i] != A[i + 1])

print(np.count_nonzero(dp))


### FIXED CODE ###

from collections import Counter
import numpy as np

A_MAX = 10 ** 6 + 1

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

dp = np.zeros(shape=A_MAX, dtype=np.int64)

if A[1] == 1:
    print(1)
elif A[1] > 1:
    print(0)
else:
    for a in A.keys():
        multiples = np.arange(a, A_MAX, a)
        np.add.at(dp, multiples, 1)

    ans = 0
    for a, count in A.items():
        if count > 1:
            continue
        if dp[a] == 1:
            ans += 1

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

n = int(input())
A = [int(input()) for _ in range(n)]

Done = []
check = 0
bot = 0
count = 0

while check == 0:
    light = A[bot]
    bot = light -1
    count += 1

    if light == 2:
        ans = count
        break
    
    if light in Done:
        ans = -1
        break

    Done.append(light)

print(ans)

### FIXED CODE ###

n = int(input())
A = [int(input()) for _ in range(n)]

bot = 1
ans = -1

for i in range(n):
    if bot == 2:
        ans = i
        break
    bot = A[bot-1]

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

from bisect import*
def main():
    root=[[],[]]
    def search_higher(key):
        ptr0,ptr1=root
        ret=None
        while ptr1:
            i=bisect(ptr0,key)
            if i!=len(ptr0):ret=ptr0[i]
            ptr0,ptr1=ptr1[i]
        i=bisect(ptr0,key)
        if i!=len(ptr0):ret=ptr0[i]
        return ret
    def search_lower(key):
        ptr0,ptr1=root
        ret=None
        while ptr1:
            i=bisect_left(ptr0,key)
            if i!=0:ret=ptr0[i-1]
            ptr0,ptr1=ptr1[i]
        i=bisect_left(ptr0,key)
        if i!=0:ret=ptr0[i-1]
        return ret
    def insert(key):
        def insert_rec(ptr):
            ptr0,ptr1=ptr
            b_size=600
            if not ptr[1]:
                insort(ptr0,key)
                if len(ptr0)==b_size*2-1:
                    ret=[ptr0[:b_size],[]]
                    ptr[0]=ptr0[b_size:]
                    return ret
            else:
                i=bisect(ptr0,key)
                tmp=insert_rec(ptr1[i])
                if tmp:
                    ptr0.insert(i,tmp[0].pop())
                    ptr1.insert(i,tmp)
                    if len(ptr1)==b_size*2:
                        ret=[ptr0[:b_size],ptr1[:b_size]]
                        ptr[0],ptr[1]=ptr0[b_size:],ptr1[b_size:]
                        return ret
        tmp=insert_rec(root)
        if tmp:root[0],root[1]=[tmp[0].pop()],[tmp,root]
    n,*a=map(int,open(0).read().split())
    l=[0]*n
    for i,v in enumerate(a,1):l[v-1]=i
    insert(0)
    insert(n+1)
    c=0
    for i,v in enumerate(l,1):
        c+=(search_higher(v)-v)*(v-search_lower(v))*i
        insert(v)
    print(c)
main()

### FIXED CODE ###

root=lambda x:x if par[x]==x else root(par[x])
same=lambda x,y:root(x)==root(y)
def unite(*z):
  x,y=map(root,z)
  if x!=y:
    if rank[x]<rank[y]:
      par[x]=y
      size[y]+=size[x]
    else:
      par[y]=x
      size[x]+=size[y]
      if rank[x]==rank[y]:rank[x]+=1
n,*a=map(int,open(0).read().split())
*par,=range(n)
rank=[1]*n
size=[1]*n
b=[0]*n
for i,t in enumerate(a):b[t-1]=i
c=0
for k in b[::-1]:
  l=r=1
  if k>0 and a[k-1]>a[k]:
    l+=size[root(k-1)]
    unite(k-1,k)
  if k+1<n and a[k+1]>a[k]:
    r+=size[root(k+1)]
    unite(k+1,k)
  c+=l*r*a[k]
print(c)
### BUGGY CODE ###

N=int(input())
A=[int(x) for x in input().split()]
while len(A)>1:
  A.sort
  
  for i in range(1,len(A)):
    A[i]=A[i]%A[0]
  
  A.sort()
  
  while A[0]==0:
    A.sort()
    if A[0]==0:
      A.pop(0)
  
print(*A)
  

### FIXED CODE ###

N=int(input())
A=[int(x) for x in input().split()]

def gcd(a,b):#最大公約数
  return a if b == 0 else gcd(b,a%b)
P=A[0]
for i in range(N):
  P=gcd(P,A[i])
print(P)
### BUGGY CODE ###



class SegmentTree:

    def __init__(self, array, aggregator):
        self.array = array
        self.aggregator = aggregator
        N = 1
        while N < len(array):
            N *= 2
        self.tree = [0]*(2*N-1)
        self.construct_tree(0, len(array)-1, 0)

    def construct_tree(self, low, high, pos):
        if low == high:
            self.tree[pos] = self.array[low]
        else:
            mid = (low+high)//2
            self.construct_tree(low, mid, 2*pos+1)
            self.construct_tree(mid+1, high, 2*pos+2)
            self.tree[pos] = self.aggregator(self.tree[2*pos+1],
                                             self.tree[2*pos+2])

    def query(self, qlow, qhigh):
        return self._query(qlow, qhigh, 0, len(self.array)-1, 0)

    def _query(self, qlow, qhigh, low, high, pos):
        if qlow <= low and high <= qhigh:
            return self.tree[pos]
        if qlow > high or qhigh < low:
            return 0
        mid = (low+high)//2
        return self.aggregator(self._query(qlow, qhigh, low, mid, 2*pos+1),
                               self._query(qlow, qhigh, mid+1, high, 2*pos+2))


    def update(self, index, value):
        self._update(index, value, 0, len(self.array)-1, 0)

    def _update(self, index, value, low, high, pos):
        if index < low or index > high:
            return
        if low == high:
            self.tree[pos] = value
        else:
            mid = (low+high)//2
            self._update(index, value, low, mid, 2*pos+1)
            self._update(index, value, mid+1, high, 2*pos+2)
            self.tree[pos] = self.aggregator(self.tree[2*pos+1], self.tree[2*pos+2])

    def __str__(self):
        start, end = 0, 1
        levels = []
        while end-1 <= len(self.tree):
            levels.append(self.tree[start:end])
            start, end = end, end+(end-start)*2
        return '\n'.join(map(str, levels))


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    N = read_int()
    h = read_ints()
    a = read_ints()
    segment_tree = SegmentTree([0]*(N+1), max)
    max_beauty = 0
    for i in range(N):
        beauty = segment_tree.query(0, h[i]-1)+a[i]
        segment_tree.update(h[i], beauty)
        max_beauty = max(max_beauty, beauty)
    return max_beauty


if __name__ == '__main__':
    print(solve())


### FIXED CODE ###




def update(tree, index, value):
    while index < len(tree):
        tree[index] = max(tree[index], value)
        index += index & -index


def read(tree, index):
    value = 0
    while index > 0:
        value = max(value, tree[index])
        index -= index & -index
    return value


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    N = read_int()
    h = read_ints()
    a = read_ints()
    tree = [0]*(N+1)
    max_beauty = 0
    for i in range(N):
        beauty = read(tree, h[i])+a[i]
        update(tree, h[i], beauty)
        max_beauty = max(max_beauty, beauty)
    return max_beauty


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

n, m = map(int, input().split())
li = [0]*(n+1)
lii = []
flag = 1
for _ in range(m):
    a, b = map(int, input().split())
    if li[a] and li[b]:
        if li[a] != li[b]:
            lii.append([li[a], li[b]])
    elif li[a] or li[b]:
        s = max(li[a],li[b])
        li[a] = s
        li[b] = s
    else:
        li[a] = flag
        li[b] = flag
        flag += 1
for i in range(len(li)):
    if li[i] == 0:
        li[i] = -i
for i in lii:
    a,b = i[0],i[1]
    for j in range(len(li)):
        if li[j] == a or li[j] == b:
            li[j] = a+b
            
from collections import Counter
result = Counter(li)
print(result.most_common(1)[0][1])


### FIXED CODE ###

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

class unionfind():
    def __init__(self,n):
        self.li = [i for i in range(n+1)]
        self.group = [1]*(n+1)

    def find(self, x):
        while self.li[x]!=x:
            x = self.li[x]
        return x

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return;
        elif x>y:
            self.li[y] = x
            self.group[x] += self.group[y]
        else:
            self.li[x] = y
            self.group[y] += self.group[x]
x = unionfind(n)
ans = 0
for _ in range(m):
    a,b = map(int,input().split())
    x.union(a,b)
print(max(x.group))
### BUGGY CODE ###

a = int(input())
i = 1
while True:
  if i % 2 == 0 and i % a == 0:
    print(i)
    break
  else:
    i += 2


### FIXED CODE ###

a = int(input())
if a % 2 == 0:
  print(a)
else:
  print(a * 2)
### BUGGY CODE ###

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

# N人の持ち点arrayの初期値を作成する
points = [K]*N

for i in range(Q):
    win = int(input()) -1
    points  = list(map(lambda x: x-1, points))
    points[win] += 1

for p in points:
    if p > 0:
        print('Yes')
    else:
        print('No')

### FIXED CODE ###

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

# N人の持ち点arrayの初期値を作成する
points = [K-Q]*N

for i in range(Q):
    win = int(input()) -1
    points[win] += 1

for p in points:
    if p > 0:
        print('Yes')
    else:
        print('No')
### BUGGY CODE ###

import numpy as np
N = int(input())

a = np.array(list(map(int,input().split())))
b = np.array(list(map(int,input().split())))
carries = [0]*30
for i in range(1,30):
    thres = pow(2,i)
    ra = np.sort(thres - (a % thres))
    rb = np.sort(b % thres)
    r = sum([N-np.searchsorted(rb,a) for a in ra])
    carries[i] = r

ans = 0
i = 0
for i in range(30):
    a1 = np.sum(a % 2)
    a0 = N - a1
    b1 = np.sum(b % 2)
    b0 = N - b1
    ans += ((a1*b0 + a0*b1 + carries[i]) % 2) << i
    a //= 2
    b //= 2
print(ans)
    










### FIXED CODE ###

import numpy as np
N = int(input())

a = np.array(list(map(int,input().split())))
b = np.array(list(map(int,input().split())))

carries = [0]*30
for i in range(1,30):
    thres = pow(2,i)
    ra = np.sort(thres - (a % thres))
    rb = np.sort(b % thres)
    #r = sum([N-np.searchsorted(rb,a) for a in ra])
    r = np.sum(N-np.searchsorted(rb,ra))
    carries[i] = r

ans = 0
i = 0
for i in range(30):
    a1 = np.sum(a % 2)
    a0 = N - a1
    b1 = np.sum(b % 2)
    b0 = N - b1
    ans += ((a1*b0 + a0*b1 + carries[i]) % 2) << i
    a //= 2
    b //= 2

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

import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
a = list(map(int,input().split()))
n += 2
ls = [0 for i in range(n*n)]
for i in range(n):
  for j in range(n):
    ls[i*n+j] = min(i,j,n-1-i,n-1-j)-1
ans = 0
st = [0]*(n*n)
for i in a:
  x,y = divmod(i-1,n-2)
  i = (x+1)*n+(y+1)
  ans += ls[i]
  st[i]=1
  q = deque([i])
  while q:
    j = q.popleft()
    for k in (j-n,j+n,j+1,j-1):
      if st[j]:
        if ls[j] < ls[k]:
          ls[k] = ls[j]
          q.append(k)
      elif ls[j]+1 < ls[k]:
        ls[k] = ls[j]+1
        q.append(k)
print(ans)

### FIXED CODE ###

import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
a = list(map(int,input().split()))
n += 2
ls = [0 for i in range(n*n)]
for i in range(n):
  for j in range(n):
    ls[i*n+j] = min(i,j,n-1-i,n-1-j)-1
ans = 0
st = [0]*(n*n)
for i in a:
  x,y = divmod(i-1,n-2)
  i = (x+1)*n+(y+1)
  ans += ls[i]
  st[i]=1
  q = deque([i])
  while q:
    j = q.popleft()
    for k in (j-n,j+n,j+1,j-1):
      if st[j]:
        if ls[j] < ls[k]:
          ls[k] = ls[j]
          q.append(k)
      elif ls[j]+1 < ls[k]:
        ls[k] = ls[j]+1
        q.append(k)
print(ans)
### BUGGY CODE ###

N=int(input())
S=list(input())



n=S.count("R")*S.count("G")*S.count("B")
count=0
for l in range(N-2):
    for r in range(l+2,N):
        m=(l+r)/2
        if m%1.0!=0:
            continue
        m=int(m)
        tmp =[S[l], S[r], S[m]]
        if len(set(tmp))==3:
            count+=1
            
            

print(n-count)
            



### FIXED CODE ###

N=int(input())
S=list(input())



n=S.count("R")*S.count("G")*S.count("B")
count=0
for l in range(N-2):
    for r in range(l+2,N):
        m=(l+r)/2
        if m%1.0!=0:
            continue
        m=int(m)
        tmp =[S[l], S[r], S[m]]
        if len(set(tmp))==3:
            count+=1
            
            

print(n-count)
### BUGGY CODE ###

# -*- coding:utf-8 -*-
import copy

INF = 2*(10**8)+1
memo = INF  # メモ化用変数

def solve():
    N, K = list(map(int, input().split(" ")))
    X = [0]
    X.extend(list(map(int, input().split(" "))))
    X.sort()

    # 幅優先探索すればいいんじゃね？

    def dfs(depth, cost, i, Xs):
        global memo
        if depth == K:
            memo = min(cost, memo)
            return cost
        
        if cost >= memo:
            # 探索を打ち切る
            return INF
        
        ret1, ret2 = INF, INF
        if i+1 < len(Xs):
            # 右に移動
            tmpCost = abs(Xs[i] - Xs[i+1])
            tmpXs = copy.deepcopy(Xs)
            del tmpXs[i]
            ret1 = dfs(depth+1, cost+tmpCost, i, tmpXs)
        if i-1 >= 0:
            # 左に移動
            tmpCost = abs(Xs[i] - Xs[i-1])
            tmpXs = copy.deepcopy(Xs)
            del tmpXs[i]
            ret2 = dfs(depth+1, cost+tmpCost, i-1, tmpXs)
        
        return min(ret1, ret2)

    # 0座標のインデックスは？
    for i in range(len(X)):
        if X[i] == 0:
            break
    ans = dfs(0, 0, i, X)
    print(ans)


if __name__ == "__main__":
    solve()

### FIXED CODE ###

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

"""解説
https://www.youtube.com/watch?v=5O4k1n5Ejzw

区間を考える問題

-30 -10 0 10 20 50

・K = 3のとき、

0座標を必ず含める、ある連続するK個のロウソクについて考える

・-30 -10 0 10
・-10 0 10 20
・0 10 20 50

左端と右端に到達する最小値を求めていけばよくて、間のロウソクは無視してよい（必ず移動中に火をつけるので）

すべての場合について求めて、その中の最小値が答え
"""
def solve():
    N, K = list(map(int, input().split()))
    X = list(map(int, input().split()))
    if 0 in X:
        # 0座標にロウソクがあるなら、火をつけるロウソクをひとつ減らしてよい
        K -= 1
    else:
        X.append(0)
    X.sort()

    origin_i = X.index(0)
    left_i = max(origin_i-K, 0)

    INF = 10**12
    ans = INF
    while left_i <= origin_i:
        if left_i+K < len(X):
            tmp1 = abs(X[left_i]-0)*2 + abs(X[left_i+K]-0)
            tmp2 = abs(X[left_i]-0) + abs(X[left_i+K]-0)*2
        else:
            break
        ans = min(ans, tmp1, tmp2)
        left_i += 1
    print(ans)

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

n = int(input())
p = list(map(int, input().split()))
count = 0
for i in range(1, n+1):
    s = min(p[:i])
    if (s == p[i-1]):
        count += 1
print(count)

### FIXED CODE ###

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

N, K = map(int, input().split())
P = tuple(map(int, input().split()))
ans = 0
for i in range(N - K + 1):
  ans = max(sum(P[i:i + K]), ans)
print((ans + K) / 2)

### FIXED CODE ###

from itertools import accumulate
N, K = map(int, input().split())
P = tuple(accumulate(map(int, input().split())))
ans = P[K - 1]
for i in range(N - K):
  ans = max(P[i + K] - P[i], ans)
print((ans + K) / 2)
### BUGGY CODE ###

A,B = map(int,input().split())
b = format(B, "b")
d_num = len(b)
digit_list = [0]*d_num
for num in range(A,B+1):
  num_str = format(num, "0"+str(d_num)+"b")
  digit_list = map(sum,zip(digit_list,[int(c) for c in num_str]))
result = [1 if digit % 2 != 0 else 0 for digit in digit_list]
print(int(''.join(map(str,result)),2))

### FIXED CODE ###

def solver(N):
  if N % 2 == 1:
    return oddodd(N)
  else:
    return (N+1) ^ oddodd(N+1)

def oddodd(N):
  return 1 if (N+1)/2 % 2 == 1 else 0 

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

print(solver(B) ^ solver(A-1))
### BUGGY CODE ###

# ANSHUL GAUTAM
# IIIT-D

from math import *
from copy import *
from string import *				# alpha = ascii_lowercase
from random import *				# l.sort(key=lambda l1:l1[0]-l1[1]) => ex: sort on the basis difference
from bisect import *				# bisect_left(arr,x,start,end)  => start and end parameters are temporary
from sys import stdin				# bisect_left return leftmost position where x should be inserted to keep sorted
from sys import maxsize
from operator import *				# d = sorted(d.items(), key=itemgetter(1))
from itertools import *
from collections import Counter		# d = dict(Counter(l))
from collections import defaultdict # d = defaultdict(list)

'''
5 2 4
'''

def solve(n,x,y):
	adj = [[] for i in range(n+1)]
	adj[x].append(y)
	adj[y].append(x)
	for i in range(1,n):
		adj[i].append(i+1)
		adj[i+1].append(i)
	# print(adj)
	ans = []
	d = {}
	for i in range(1,n):
		d[i] = 0
	for k in range(1,n+1):
		q = [k]
		dis = [maxsize]*(n+1)
		dis[k] = 0
		while(q):
			src = q.pop()
			for nn in adj[src]:
				if(dis[nn] > dis[src]+1):
					dis[nn] = dis[src] + 1
					q.append(nn)
		curr = 0
		# print('k:',k,dis)
		for ii in range(k+1,n+1):
			d[dis[ii]] += 1
	return d

N,X,Y = list(map(int, stdin.readline().rstrip().split()))
ans = solve(N,X,Y)
for i in range(1,N):
	print(ans[i])



### FIXED CODE ###

# ANSHUL GAUTAM
# IIIT-D

from math import *
from copy import *
from string import *				# alpha = ascii_lowercase
from random import *				# l.sort(key=lambda l1:l1[0]-l1[1]) => ex: sort on the basis difference
from bisect import *				# bisect_left(arr,x,start,end)  => start and end parameters are temporary
from sys import stdin				# bisect_left return leftmost position where x should be inserted to keep sorted
from sys import maxsize
from operator import *				# d = sorted(d.items(), key=itemgetter(1))
from itertools import *
from collections import Counter		# d = dict(Counter(l))
from collections import defaultdict # d = defaultdict(list)

'''
5 2 4
'''

def solve(n,x,y):
	adj = [[] for i in range(n+1)]
	adj[x].append(y)
	adj[y].append(x)
	for i in range(1,n):
		adj[i].append(i+1)
		adj[i+1].append(i)
	# print(adj)
	ans = []
	d = {}
	for i in range(1,n):
		d[i] = 0
	for k in range(1,n+1):
		q = [k]
		dis = [maxsize]*(n+1)
		dis[k] = 0
		while(q):
			src = q.pop()
			for nn in adj[src]:
				# if(nn > k or nn == X or nn == Y):
				if(dis[nn] > dis[src]+1):
					# if(src == 4):
						# print('src:',src,'nn:',nn)
					dis[nn] = dis[src] + 1
					q.append(nn)
				# else:
				# 	dis[nn] = 
			# if(k == 3):
			# 	print('src:',src)
			# 	print('dis:',dis)
		curr = 0
		# if(k == 3):
		# print('k:',k,dis)
		for ii in range(k+1,n+1):
			d[dis[ii]] += 1
	return d

N,X,Y = list(map(int, stdin.readline().rstrip().split()))
ans = solve(N,X,Y)
for i in range(1,N):
	print(ans[i])
### BUGGY CODE ###

INF = 10**18

N = int(input())
T = list(map(int, input().split()))
V = list(map(int, input().split()))
V = [0] + V + [0]
R = [(0, 0)]*(N+2)
for i in range(1,N+1):
    R[i] = (R[i-1][1], R[i-1][1] + T[i-1])
R[N+1] = (R[N][1], R[N][1])
def velocity(i, x):
    if x < R[i][0]:
        return V[i]+R[i][0]-x
    elif R[i][0] <= x <= R[i][1]:
        return V[i]
    else:
        return V[i]+x-R[i][1]
ans = 0
dp = [0]*(R[N+1][1]*2+1)
for x in range(1, R[N+1][1]*2+1):
    mi = INF
    for i in range(N+2):
        mi = min(velocity(i, x/2), mi)
    dp[x] = mi
    ans += 0.25*(dp[x-1]+mi)
print(ans)


### FIXED CODE ###

INF = 10**18

N = int(input())
T = list(map(int, input().split()))
V = list(map(int, input().split()))
V = [0] + V + [0]
R = [(0, 0)]*(N+2)
for i in range(1,N+1):
    R[i] = (R[i-1][1], R[i-1][1] + T[i-1])
R[N+1] = (R[N][1], R[N][1])
def velocity(i, x):
    if x < R[i][0]:
        return V[i]+R[i][0]-x
    elif R[i][0] <= x <= R[i][1]:
        return V[i]
    else:
        return V[i]+x-R[i][1]
ans = 0
dp = [0]*(R[N+1][1]*2+1)
for x in range(1, R[N+1][1]*2+1):
    mi = INF
    for i in range(N+2):
        mi = min(velocity(i, x/2), mi)
    dp[x] = mi
    ans += 0.25*(dp[x-1]+mi)
print(ans)
### BUGGY CODE ###

S = list(input())
T = list(input())
N = len(S)

for i in range(N):
    if S.count(S[i]) != T.count(T[i]):
        print('No')
        break
else:
    print('Yes')


### FIXED CODE ###

S = list(input())
T = list(input())
N = len(S)

a = ord('a')
alf = []
for i in range(26):
     alf.append(chr(a))
     a += 1

SN = [[] for i in range(26)]
TN = [[] for i in range(26)]
for i in range(N):
    for j in range(26):
        if alf[j] == S[i]:
            SN[j].append(i)
        if alf[j] == T[i]:
            TN[j].append(i)
SN.sort()
TN.sort()
print('Yes' if SN == TN else 'No')
### BUGGY CODE ###

n = int(input())
def total(n):
    total = 0
    for i in range(len(str(n))):
        total += int(str(n)[i])
        if i == len(str(n)):
            total(total)
    
    return total

if total(n) %9 == 0:
    print("Yes")
else:
    print("No")

### FIXED CODE ###

n = int(input())
total = 0

for i in str(n):
    total += int(i)

if total %9 == 0:
    print("Yes")
else:
    print("No")
### BUGGY CODE ###

from math import floor
a, b = map(int, input().split())

for i in range(int(10e+20)):
    if floor(i*0.08) == a:
        if floor(i*0.1) == b:
            break

print(i)

### FIXED CODE ###

import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
A,B = map(int,read().split())
 
def test(n):
    x = n * 8 // 100
    y = n * 10 // 100
    return (x == A) and (y == B)
 
answer = -1
for n in range(20000):
    if test(n):
        answer = n
        break
print(answer)
### BUGGY CODE ###

from collections import defaultdict as dd
from collections import deque
N, M = map(int, input().split())
e = dd(list)
inf = 10 ** 9
for _ in range(M):
  u, v = map(int, input().split())
  e[u].append(v)
S, T = map(int, input().split())

stopped = [inf] * (N + 1)
Q = deque()
Q.append(S)
stopped[S] = 0
while len(Q) != 0:
  p = Q.popleft()
  if stopped[p] >= stopped[T]:
    break
  for q in e[p]:
    for r in e[q]:
      for s in e[r]:
        if stopped[s] > stopped[p] + 1:
          Q.append(s)
          stopped[s] = stopped[p] + 1
if stopped[T] == inf:
  print(-1)
else:
  print(stopped[T])

### FIXED CODE ###

from collections import defaultdict as dd
from collections import deque
N, M = map(int, input().split())
e = dd(list)
inf = 10 ** 9
for _ in range(M):
  u, v = map(int, input().split())
  e[u].append(v + N)
  e[u + N].append(v + 2 * N)
  e[u + 2 * N].append(v)
S, T = map(int, input().split())
S += 2 * N
T += 2 * N
stopped = [inf] * (3 * (N + 1))
Q = deque()
Q.append(S)
stopped[S] = 0
while len(Q) != 0:
  p = Q.popleft()
  if stopped[p] >= stopped[T]:
    break
  for q in e[p]:
    if stopped[q] > stopped[p] + 1:
      Q.append(q)
      stopped[q] = stopped[p] + 1
if stopped[T] == inf:
  print(-1)
else:
  print(stopped[T] // 3)
### BUGGY CODE ###

# -*- coding: utf-8 -*-
def paint(i, c):  # i = 0, 1, 2
    cost = 0
    for row in range(N):
        for col in range(N):
            if (row + col) % 3 == i:
                cost += D[G[row][col] - 1][c - 1]

    return cost


def cost(comb):
    cost = 0
    for i in range(3):
        cost += paint(i, comb[i])

    return cost


if __name__ == '__main__':
    from itertools import permutations
    N, C = map(int, input().split())
    D = [[int(_) for _ in input().split()] for i in range(C)]
    G = [[int(_) for _ in input().split()] for i in range(N)]
    combs = permutations(range(1, C + 1), 3)
    min_cost = min([cost(comb) for comb in combs])
    print(min_cost)


### FIXED CODE ###

# -*- coding: utf-8 -*-
N, C = map(int, input().split())

D = []
for c in range(C):
    D.append([int(d) for d in input().split()])

Gmod = [[0 for i in range(C)] for i in range(3)]
for n in range(N):
    for m, g in enumerate(input().split()):
        Gmod[(n + m) % 3][int(g) - 1] += 1

K = []
for c0 in range(C):
    d0 = sum([Gmod[0][c] * D[c][c0] for c in range(C)])
    for c1 in [i for i in range(C) if not i == c0]:
        d1 = sum([Gmod[1][c] * D[c][c1] for c in range(C)])
        for c2 in [i for i in range(C) if (not i == c0) and (not i == c1)]:
            d2 = sum([Gmod[2][c] * D[c][c2] for c in range(C)])
            K.append(d0 + d1 + d2)

print(min(K))