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

import collections
i,j = 0,0 
s = raw_input()
q = collections.deque([])
while(j < len(s)):
	while(j < len(s) and s[j] == s[i]): j+=1
	q.append(j - i - 1)
	j = i

#5 6 5 1 1 4 2 1 1 1 1 1
ns = len(s)
while(len(q) > 1):
	u,v = q.popleft(), q.popleft()
	if q: q[0] += abs(u-v)
print ns - (q[0] if q else 0)


### FIXED CODE ###

import collections

s = raw_input()
stack = collections.deque([])
i = 0
j = 0
while(j < len(s)):
	while(j < len(s) and s[i] == s[j]): j += 1	
	stack.append(j-i)
	i = j
n = len(s)
while(len(stack) > 1) :
	v = stack.pop()
	u = stack.pop()
	if v > u: 
		if stack:
			stack[-1] += v-u
		else:
			stack.append(v-u)
	elif v < u: stack.append( u - v)

print n - (stack[-1] if stack else 0)
### BUGGY CODE ###

N, x = map(int, input().split())
a = list(map(int, input().split()))

count = 0

for i, c in enumerate(a):
	try:
		j = a[i + 1]
	except IndexError:
		break

	while (a[i + 1] + c) > x:
		if (a[i + 1] + c) == x:
			break
		count += 1
		a[i + 1] -= 1
	else:
		continue

print(count)

### FIXED CODE ###

N, x = map(int, input().split())
a = list(map(int, input().split()))

count = 0

for i, c in enumerate(a):
	try:
		j = a[i + 1]
	except IndexError:
		break
	while (a[i + 1] + c) > x:
		if (a[i + 1] + c) == x:
			break
		count += abs(x - (a[i + 1] + c))
		a[i + 1] -= abs(x - (a[i + 1] + c))
		if a[i + 1] <= 0:
			a[i + 1] = 0
			break
	else:
		continue

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

from copy import deepcopy
dx=[0,0,1,-1]
dy=[1,-1,0,0]

def dfs(y,x,cnt):
    Ice_cp[y][x]=0
    cnt+=1
    for i in range(4):
        mx=x+dx[i]
        my=y+dy[i]
        if 0<=mx<m and 0<=my<n and Ice_cp[my][mx]==1:
            return dfs(my,mx,cnt)
    return cnt

while True:
    m=input()
    n=input()
    if n==m==0:break
    maxInt=0
    Ice=[map(int,raw_input().split()) for i in range(n)]
    for i in range(n):
        for j in range(m):
            cnt=0
            Ice_cp=deepcopy(Ice)
            if Ice_cp[i][j]==1:
                maxInt=max(maxInt,dfs(i,j,cnt))
    print maxInt

### FIXED CODE ###

dx=[0,0,1,-1]
dy=[1,-1,0,0]

def dfs(y,x,cnt):
    global maxInt
    maxInt=max(maxInt,cnt)
    Ice[y][x]=0
    for i in range(4):
        mx=x+dx[i]
        my=y+dy[i]
        if mx<0 or m<=mx or my<0 or n<=my:
            continue
        if Ice[my][mx]==1:
            dfs(my,mx,cnt+1)
            Ice[my][mx]=1

while True:
    m=input()
    n=input()
    if n==m==0:break
    maxInt=0
    Ice=[map(int,raw_input().split()) for i in range(n)]
    for y in range(n):
        for x in range(m):
            if Ice[y][x]==1:
                dfs(y,x,1)
                Ice[y][x]=1
    print maxInt
### BUGGY CODE ###

import numpy as np
import sys
input = sys.stdin.readline


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

    for _ in range(K):
        B = np.zeros(N)
        for i, a in enumerate(A):
            bottom = i - a
            top = i + a + 1
            if bottom < 0:
                bottom = 0
            if top > N:
                top = N
            B[bottom:top] += np.ones(top-bottom)
        A = list(map(int, B))

    ans = ' '.join(list(map(str, A)))
    print(ans)


if __name__ == '__main__':
    main()


### FIXED CODE ###

from numba import jit
import sys
input = sys.stdin.readline


@jit
def main():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))

    for _ in range(K):
        B = [0]*(N+1)
        for i, a in enumerate(A):
            B[max(0, i-a)] += 1
            B[min(N, i+a+1)] -= 1
        for j in range(1, N):
            B[j] += B[j-1]
        if A == B[:-1]:
            A = B[:-1]
            break
        A = B[:-1]

    ans = ' '.join(list(map(str, A)))
    print(ans)


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

N = int(input())
D = [int(a) for a in input().split()]

num_at_dist = [1] + [0] * (N-1) + [0] # extra 0 at the end for index -1

if D[0] != 0:
    ans = 0
else:
    ans = 1
    D.sort()
    for i in range(1, N):
        dist = D[i]
        num_at_dist[dist] += 1
        ans *= num_at_dist[dist - 1]

print(ans % 998244353)


### FIXED CODE ###

import numpy as np

N = int(input())
D = np.array([int(a) for a in input().split()])

num_at_dist = np.array([1] + [0] * (N-1) + [0]) # extra 0 at the end for index -1

if D[0] != 0:
    ans = 0
else:
    ans = 1
    D = np.sort(D)
    for i in range(1, N):
        dist = D[i]
        num_at_dist[dist] += 1
        ans = ( ans * num_at_dist[dist - 1] ) % 998244353

print(ans % 998244353)
### BUGGY CODE ###

h,n=map(int,input().split())
ab=[list(map(int,input().split()))for _ in range(n)]
maxa=max([a for a,b in ab])
maxmp=pow(10,8)
dp=[maxmp]*(h+maxa) # dp[i]:ダメージをぴったりi与えるのに必要な最小魔力
dp[0]=0
for i in range(h+maxa):
  b=[dp[i-a]+b for a,b in ab if i-a>=0]
  dp[i]=min(dp[i],min(b)) if b else dp[i]
print(min(dp[h:]))

### FIXED CODE ###

import numpy as np
h,n=map(int,input().split())
ab=np.array([list(map(int,input().split())) for _ in range(n)])
dp=np.zeros(10**4+1,np.int64) #dp[i]:残り体力がiのとき、倒すまでの最小魔力
dp[0]=0
for a,b in ab:
      dp[1:a+1]=np.minimum(dp[1:a+1],b)
# a:減らせる体力
# b:魔力
for i in range(1,h+1):
  dp[i]=np.min(dp[i-ab[:,0]]+ab[:,1])
print(dp[h])
### BUGGY CODE ###

from itertools import groupby
import copy
def calc():
  s = 0
  for i in range(h):
    gr = groupby(g[i])
    j = 0
    for key,it in gr:
      if key==-1: continue
      l = len(list(it))
      if l >= K:
        for k in range(l):
          g[i][j+k] = -1
        # print("s", key, l, key*l)
        s += key*l
      j += l
      # print("j", j)
  return s

def flatten():
  for j in range(w):
    lst = []
    for i in range(h-1, -1, -1):
      if g[i][j] > 0:
        lst.append(g[i][j])

    lst += [-1] * (h - len(lst))

    for i in range(h-1, -1, -1):
      g[i][j] = lst[h-i-1]

h,w,K = map(int,input().split())
mat = []
for _ in range(h):
  mat.append([int(e) for e in list(input())])

res = 0
for i in range(h):
  for j in range(w):
    score = 0
    g = copy.deepcopy(mat)
    g[i][j] = -1
    time = 0
    flatten()
    while True:
      s = calc()
      if s > 0:
        score += pow(2, time) * s
      else:
        break
      flatten()
      time += 1
    res = max(res, score)

print(res)



### FIXED CODE ###

from itertools import groupby

def calc(time):
  t = 0
  for i in range(h):
    gr = groupby(g[i])
    lst = []
    p = 0
    for key,it in gr:
      j = len(list(it))
      lst.append([p,key,j])
      p += j
    for j in range(len(lst)):
      if lst[j][1] == -1:
        continue
      if lst[j][2] >= K:
        t += (2**time)*lst[j][1]*lst[j][2]
        for k in range(lst[j][0],lst[j][0]+lst[j][2]):
          g[i][k] = 0

  return t

def flatten():
  for j in range(w):
    lst = []
    for i in range(h-1, -1, -1):
      if g[i][j] > 0:
        lst.append(g[i][j])

    lst += [-1] * (h - len(lst))

    for i in range(h-1, -1, -1):
      g[i][j] = lst[h-i-1]

h,w,K = map(int,input().split())
mat = [ [int(e) for e in list(input())] for _ in range(h) ]

res = 0
for i in range(h):
  for j in range(w):
    score = 0
    g = [ [ mat[n][m] for m in range(w) ] for n in range(h) ]
    g[i][j] = -1
    time = 0
    flatten()
    while True:
      s = calc(time)
      if s==0: break
      score += s
      flatten()
      time += 1
    res = max(res, score)

print(res)
### BUGGY CODE ###

N = int(input())
A = []
c = 0
for n in input().split():
  i = int(n)
  A.append(i)
A.sort()
for i in range(N):
  Ai = A[i]
  if i != N - 1:
    if Ai == A[i + 1]:
      continue
  flg = True
  for j in range(i):
    Aj = A[j]
    if Ai % Aj == 0:
      flg = False
      break
  if flg:
    c += 1
print(c)
    
    

### FIXED CODE ###

N = int(input())
c=[0]*8**7
for a in input().split():
    c[int(a)] += 1
i=r=0
for t in c:
    if t:
        c[::i]=[0]*-(-8**7//i)
    i+=1
    r+=t==1
print(r)
### BUGGY CODE ###

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

n,u,v = map(int, input().split())
adjacent_list = [[] for i in range(n+1)]
aoki = [0 for i in range(n+1)]
takahashi = [0 for i in range(n+1)]
for i in range(n-1):
    a,b = map(int ,input().split())
    adjacent_list[a].append(b)
    adjacent_list[b].append(a)

def dfs(node, count,li):
    global node_par
    li[node] = count
    finished.add(node)
    for i in adjacent_list[node]:
        if i not in finished:
            node_par[i] = node
            dfs(i, count + 1,li)
        
node_par = [0 for i in range(n+1)]

finished = set()
dfs(u,0,takahashi)

#辿って親保存しとく
finished = set()
dfs(v,0,aoki)

#さかのぼれるとこまで行く,startがさかのぼれる最大のノーど
par = u
start = u
while takahashi[par] < aoki[par]:
    start = par
    par = node_par[start]

ans_height = [0 for i in range(n+1)]
finished = set([node_par[start]])
dfs(start,0,ans_height)
print(max(ans_height) + aoki[start] - 1)


### FIXED CODE ###

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

n,u,v = map(int, input().split())
adjacent_list = [[] for i in range(n+1)]
aoki = [0 for i in range(n+1)]
takahashi = [0 for i in range(n+1)]
for i in range(n-1):
    a,b = map(int ,input().split())
    adjacent_list[a].append(b)
    adjacent_list[b].append(a)

def dfs(node, count,li):
    global node_par
    li[node] = count
    finished.add(node)
    for i in adjacent_list[node]:
        if i not in finished:
            node_par[i] = node
            dfs(i, count + 1,li)
        
node_par = [0 for i in range(n+1)]

finished = set()
dfs(u,0,takahashi)

#辿って親保存しとく
finished = set()
dfs(v,0,aoki)

#さかのぼれるとこまで行く,startがさかのぼれる最大のノーど
par = u
start = u
while takahashi[par] < aoki[par]:
    start = par
    par = node_par[start]

ans_height = [0 for i in range(n+1)]
finished = set([node_par[start]])
dfs(start,0,ans_height)
print(max(ans_height) + aoki[start] - 1)
### BUGGY CODE ###

str_len = int(input().rstrip())
str = input().rstrip()

rgb_nums_dict = {'R':str.count('R'), 'G':str.count('G'), 'B':str.count('B')}
total = 0
for i in range(str_len-2):
    for j in range(i+1,str_len-1):
        first_str = str[i]
        second_str = str[j]
        if first_str==second_str:
            continue
        else:
            if 2*j-i<str_len and second_str!=str[2*j-i]!=first_str:
                total-=1
                

for letter in str:
    first_str = letter
    
    if first_str=='R':
        total += rgb_nums_dict['G']*rgb_nums_dict['B']
        
    elif first_str=='G':
        total += rgb_nums_dict['R']*rgb_nums_dict['B']
        
    else:#'B'
        total += rgb_nums_dict['R']*rgb_nums_dict['G']
        
    rgb_nums_dict[first_str]-=1
    if rgb_nums_dict[first_str]==0:
        break

print(total)


### FIXED CODE ###

str_len = int(input().rstrip())
str = input().rstrip()

rgb_nums_dict = {'R':str.count('R'), 'G':str.count('G'), 'B':str.count('B')}
total = 0
for i in range(str_len-2):
    for j in range(i+1,str_len-1):
        first_str = str[i]
        second_str = str[j]
        if first_str==second_str:
            continue
        else:
            if 2*j-i<str_len and second_str!=str[2*j-i]!=first_str:
                total-=1
                


for i in range(str_len):
    first_str = str[i]
    if first_str=='R':
        total += rgb_nums_dict['G']*rgb_nums_dict['B']
        
    elif first_str=='G':
        total += rgb_nums_dict['R']*rgb_nums_dict['B']
        
    else:#'B'
        total += rgb_nums_dict['R']*rgb_nums_dict['G']
        
    rgb_nums_dict[first_str]-=1
    if rgb_nums_dict[first_str]==0:
        break
    
print(total)
### BUGGY CODE ###

N=int(input())
A=list(map(int,input().split()))
for i in range(1,N+1):
    if i in A:
        print(len([j for j in A if j == i]))
        while i in A:
            A.remove(i)
    else:
        print(0)



### FIXED CODE ###

N=int(input())
A=list(map(int,input().split()))
B=list(range(1, N + 1))
import collections
new_A=collections.Counter(A)
for i in B:
    print(new_A[i])
### BUGGY CODE ###

n, k = map(int, input().split())
s = list(map(int, input()))
count_1 = 0


def re_cum_list(li):
  count_0 = 0
  count_1 = 0
  re_li = []
  for i in li:
    if i == 0:
      count_0 -= 1
      if count_1 > 0:
        re_li.append(count_1)
        count_1 = 0
    else:
      count_1 += 1
      if count_0 < 0:
        re_li.append(count_0)
        count_0 = 0
  if count_1 > 0:
    re_li.append(count_1)
  if count_0 < 0:
    re_li.append(count_0)
  return re_li


cum_1_s = re_cum_list(s)

sum_list = []
su = 0
count = 0
j = 0
while j <= len(cum_1_s):
  for i in range(j, len(cum_1_s)):
    if cum_1_s[i] > 0:
      pass
    else:
      if count >= k:
        break
      count += 1
    su += abs(cum_1_s[i])
  sum_list.append(su)
  j += 1
  count = 0
  su = 0


print(max(sum_list))

### FIXED CODE ###

from collections import deque
N, K = map(int, input().split())
S = deque(input())
T = []
P = []
pre = S[0]
cnt = 0
while S:
  s = S.popleft()
  cnt += 1
  if pre != s:
    cnt -= 1
    T += [cnt]
    P += [pre]
    pre = s
    cnt = 1
T += [cnt]
P += [pre]

cum_T = T[:]
for i in range(len(T)-1):
  cum_T[i+1] = cum_T[i] + T[i+1]

cum_T += [0]
l = len(P)
ans = 0
for i in range(l):
  if P[i] == '1':
    r = min(l-1, i+2*K)
    ans = max(ans,-cum_T[i-1]+cum_T[r] )
  else:
    r = min(l-1, i+2*K-1)
    ans = max(ans, -cum_T[i-1]+cum_T[r])
print(ans)
### BUGGY CODE ###

def calc_point(points, n):
    for i in range(len(points)):
        if i != n:
            points[i] -= 1


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

points = []
for i in range(n):
    points.append(k)

for i in range(q):
    a = int(input())
    calc_point(points, a-1)


for i in range(len(points)):
    if points[i] <= 0:
        print("No")
    else:
        print("Yes")



### FIXED CODE ###

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

points = {}

for i in range(q):
    a = int(input())
    if a not in points:
        points[a] = 0
    points[a] += 1


for i in range(n):
    p = 0
    if (i+1) in points:
        p = points[i+1]
    if k - q+p >= 1:
        print("Yes")
    else:
        print("No")
### BUGGY CODE ###

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

ta = [[0] * (M+1) for i in range(N+1)]
ta[0][0]=1
wa = [[0] * (M+1) for i in range(N+1)]
wa[0][:]=[1]*(M+1)
for i in range(N+1):
    wa[i][0]=1
output = 1
for i in range(1,N+1):
    for j in range(1,M+1):
        if S[i-1]==T[j-1]:
            ta[i][j]=wa[i-1][j-1]
            wa[i][j]=wa[i-1][j]+wa[i][j-1]
        else:
            wa[i][j]=wa[i-1][j]+wa[i][j-1]-wa[i-1][j-1]
output = wa[N][M]%(10**9+7)
print(int(output))

### FIXED CODE ###

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

ta = [[0] * (M+1) for i in range(N+1)]
ta[0][0]=1
wa = [[0] * (M+1) for i in range(N+1)]
wa[0][:]=[1]*(M+1)
for i in range(N+1):
    wa[i][0]=1
output = 1
for i in range(1,N+1):
    for j in range(1,M+1):
        if S[i-1]==T[j-1]:
            ta[i][j]=wa[i-1][j-1]
            wa[i][j]=(wa[i-1][j]+wa[i][j-1])%(10**9+7)
        else:
            wa[i][j]=(wa[i-1][j]+wa[i][j-1]-wa[i-1][j-1]+(10**9+7))%(10**9+7)
output = wa[N][M]
print(int(output))
### BUGGY CODE ###

def ctoi(c):
  return ord(c)-97

n=int(input())
s=list(input())

bits=[[0]*(n+1) for _ in range(26)]

def query(pos):
  ret=[0]*26
  for i in range(26):
    tmp=0
    p=pos
    while p>0:
      tmp+=bits[i][p]
      p-=p&(-p)
    ret[i]=tmp
  return ret

def update(pos,a,x):
  while pos<=n:
    bits[a][pos]+=x
    pos+=pos&(-pos)

for i in range(n):
  update(i+1,ctoi(s[i]),1)

q=int(input())
for _ in range(q):
  flag,a,b=map(str,input().split())
  flag=int(flag)
  a=int(a)
  if flag==1:
    if s[a-1]==b:
      continue
    else:
      update(a,ctoi(s[a-1]),-1)
      update(a,ctoi(b),1)
      s[a-1]=b
  elif flag==2:
    b=int(b)
    cnt1=query(b)
    cnt2=query(a-1)
    ans=0
    for i in range(26):
      if cnt1[i]-cnt2[i]>0:
        ans+=1
    print(ans)

### FIXED CODE ###

def ctoi(c):
  return ord(c)-97

n=int(input())
s=list(input())

bits=[[0]*(n+1) for _ in range(26)]

def query(pos):
  ret=[0]*26
  for i in range(26):
    tmp=0
    p=pos
    while p>0:
      tmp+=bits[i][p]
      p-=p&(-p)
    ret[i]=tmp
  return ret

def update(pos,a,x):
  while pos<=n:
    bits[a][pos]+=x
    pos+=pos&(-pos)

for i in range(n):
  update(i+1,ctoi(s[i]),1)

q=int(input())
for _ in range(q):
  flag,a,b=map(str,input().split())
  flag=int(flag)
  a=int(a)
  if flag==1:
    if s[a-1]==b:
      continue
    else:
      update(a,ctoi(s[a-1]),-1)
      update(a,ctoi(b),1)
      s[a-1]=b
  elif flag==2:
    b=int(b)
    cnt1=query(b)
    cnt2=query(a-1)
    ans=0
    for i in range(26):
      if cnt1[i]-cnt2[i]>0:
        ans+=1
    print(ans)
### BUGGY CODE ###

n, k = map(int, input().split())
a = [int(an) for an in input().split()]
ans = 0
set_a = set(a)
num_of_types = len(set_a)
if num_of_types > k:
  ans = sum(sorted([a.count(num) for num in set_a])[:num_of_types - k])
print(ans)

### FIXED CODE ###

from collections import Counter

n, k = map(int, input().split())
a = [int(an) for an in input().split()]
ans = 0
set_a = set(a)
num_of_types = len(set_a)
if num_of_types > k:
  cnt = Counter(a)
  ans = sum(sorted(cnt.values())[: num_of_types - k])

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

def open(box, key):
    n = 0
    for i in range(N):
        if (box>>i & 1) - (key>>i & 1) >= 1:
            n += 2**i
    return n
N, M = map(int, input().split())
INF = 10**8+1
dp = [[INF]*2**(N+1) for i in range(M+1)]
for i in range(M+1):
    dp[i][0] = 0
key = []
for i in range(M):
    a, b= map(int, input().split())
    n = 0
    c = list(map(int, input().split()))
    for i in range(b):
        n += 2**(c[i]-1)
    key.append((a,n)) 
for i in range(1,M+1):
    for j in range(2**(N+1)):
        dp[i][j] = min(dp[i-1][j], dp[i-1][open(j, key[i-1][1])]+key[i-1][0])
if dp[M-1][2**(N+1)-1] == INF:
    dp[M-1][2**(N+1)-1] = -1
print(dp[M-1][2**(N+1)-1])

### FIXED CODE ###

def open(box, key):
    return (box & (2**N-1 - key))
N, M = map(int, input().split())
INF = 10**8+1
dp = [[INF]*2**N for i in range(M+1)]
for i in range(M+1):
    dp[i][0] = 0
key = []
for i in range(M):
    a, b= map(int, input().split())
    n = 0
    c = list(map(int, input().split()))
    for i in range(b):
        n += 2**(c[i]-1)
    key.append((a,n))
for i in range(1,M+1):
    for j in range(2**N):
        dp[i][j] = min(dp[i-1][j], dp[i-1][open(j, key[i-1][1])]+key[i-1][0])
if dp[M-1][2**N-1] == INF:
    dp[M-1][2**N-1] = -1
print(dp[M-1][2**N-1])
### BUGGY CODE ###

import numpy as np
#from itertools import combinations as comb
#from itertools import combinations_with_replacement as comb_with

#A = int(input())
N,K,Q= map(int,input().split())
#A = list(map(int,input().split()))
#B = list(map(int,input().split()))
#S= str(input())
l=np.zeros(N)
l+=K
#print(l)
for m in range(Q):
    A = int(input())
    l-=1
    l[A-1]+=1
#    print(l)
l=np.where(l<1,'No','Yes')
for i in l:
    print(i)


### FIXED CODE ###

import numpy as np
#from itertools import combinations as comb
#from itertools import combinations_with_replacement as comb_with

#A = int(input())
N,K,Q= map(int,input().split())
#A = list(map(int,input().split()))
#B = list(map(int,input().split()))
#S= str(input())
l=np.zeros(N)
l+=(K-Q)
#print(l)
for m in range(Q):
    A = int(input())
    l[A-1]+=1
#    print(l)
l=np.where(l<1,'No','Yes')
for i in l:
    print(i)
### BUGGY CODE ###

# -*- coding: utf-8 -*-
import sys
from itertools import permutations

i = sys.stdin
N, C = map(int, i.readline().strip().split())
D, G = [], []
for c in range(C):
    D += [int(_) for _ in i.readline().strip().split()]
for n in range(N):
    G += [int(_) for _ in i.readline().strip().split()]

table0 = [0 for c in range(C)]
table1 = [0 for c in range(C)]
table2 = [0 for c in range(C)]
for row in range(N):
    for col in range(N):
        i = (row + col) % 3
        for c in range(C):
            if i == 0:
                table0[c] += D[(G[row * N + col] - 1) * C + c]
            elif i == 1:
                table1[c] += D[(G[row * N + col] - 1) * C + c]
            else:
                table2[c] += D[(G[row * N + col] - 1) * C + c]

cst = 1000 * 500**2
combs = permutations(range(C), 3)
for comb in combs:
    cst = min(cst, table0[comb[0]] + table1[comb[1]] + table2[comb[2]])

print(cst)


### 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))
### BUGGY CODE ###

import collections

input()
a = [int(x) for x in input().split()]
print(max(collections.Counter([max(a[i + 1:]) - x for i, x in enumerate(a[:-1])]).items())[1])


### FIXED CODE ###

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

lowest = a[0]
lowests = {a[0]}
diff = -1
pairs = []

for x in a[1:]:
    if lowest > x:
        lowests = {x}
        lowest = x
    elif lowest == x:
        lowests.add(x)
    elif diff == x - lowest:
        pairs += [(x, y) for y in lowests]
    elif diff < x - lowest:
        pairs = [(x, y) for y in lowests]
        diff = x - lowest

a, b = zip(*pairs)
print(min(len(set(a)), len(set(b))))
### BUGGY CODE ###

N = int(input())
dp = [1] * (N+1)
for i in range(2, N+1):
    k = 1
    while i * k <= N:
        dp[i*k] += 1
        k += 1
ans = 0
for i in range(1, N+1):
    ans += i * dp[i]
print(ans)


### FIXED CODE ###

N = int(input())
dp = [1] * (N+1)
for i in range(2, N+1):
    k = 1
    while i * k <= N:
        dp[i*k] += 1
        k += 1
ans = 0
for i in range(1, N+1):
    ans += i * dp[i]
print(ans)
### BUGGY CODE ###

import math  # noqa
import bisect  # noqa
import queue  # noqa


if __name__ == '__main__':
    N, M = map(int, input().split())
    A = list(map(int, input().split()))

    que = queue.PriorityQueue()
    for a in A:
        que.put(a)

    for _ in range(M):
        B, C = map(int, input().split())
        for i in range(0, B):
            a = que.get()
            if a < C:
                que.put(C)
            else:
                que.put(a)
                break

    ans = 0
    while not que.empty():
        ans += que.get()

    print(ans)


### FIXED CODE ###

import math  # noqa
import bisect  # noqa
import queue  # noqa


if __name__ == '__main__':
    N, M = map(int, input().split())
    A = list(map(int, input().split()))

    cnt = {}
    for a in A:
        if a not in cnt:
            cnt[a] = 1
        else:
            cnt[a] += 1

    for _ in range(M):
        B, C = map(int, input().split())
        if C not in cnt:
            cnt[C] = B
        else:
            cnt[C] += B

    cnt = [[k, v] for k, v in cnt.items()]
    cnt.sort(reverse=True)

    ans = 0
    for k, v in cnt:
        if N <= v:
            ans += k * N
            break
        else:
            ans += k * v
            N -= v

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

N = int(input())
S = input()
Bsum = [0] #境界より左にある黒の数
Wsum = [0] #境界より右にある白の数
for i in range(N):
    Bsum = Bsum + [Bsum[-1]+(1 if S[i]=="#" else 0) ]
    Wsum = [Wsum[0]+(1 if S[N-i-1]=="." else 0)] + Wsum
print(min([Bsum[i]+Wsum[i] for i in range(N+1)]))

### FIXED CODE ###

N = int(input())
S = input()
Bsum = [0] #境界より左にある黒の数
Wsum = [0] #境界より右にある白の数
for i in range(N):
    Bsum += [Bsum[-1]+(1 if S[i]=="#" else 0) ]
    Wsum += [Wsum[-1]+(1 if S[N-i-1]=="." else 0)]
print(min([Bsum[i]+Wsum[N-i] for i in range(N+1)]))