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


import numpy as np
N , K ,Q = map(int, input().split())
initializer_list = np.full(N,K,dtype='float32')
for _ in range(Q):
    i = int(input())-1
    tmp = initializer_list[i]
    initializer_list -=1
    initializer_list[i] = tmp

[print('Yes') if i > 0 else print('No')  for i in initializer_list]


### FIXED CODE ###

import numpy as np
N , K ,Q = map(int, input().split())
initializer_list = [0] * N
for _ in range(Q):
    i = int(input())-1
    initializer_list[i] += 1
    

[print('Yes') if (Q - initializer_list[i] < K) else print('No')  for i in range(N)]
### BUGGY CODE ###

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

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

def LI(): return list(map(int,input().split()))
def II(): return int(input())
def LS(): return input().split()
def S(): return input()

def main():
  n,m=LI()
  l=LI()

  l.sort()
  sm=sum(l)

  l3=[]
  for i in range(m):
    a,b=LI()
    l3.append([b,a])
  l3=sorted(l3,key=lambda x:x[0],reverse=True)

  n2=0
  for x in l3:
    n2+=x[1]

  # if n>n2:
  i=0
  i2=0
  while True:
    if i2>m-1:
      break

    a,b=l3[i2]
    while True:
      if i>n-1:
        break

      if b==0:
        i2+=1
        break

      x=l[i]
      if x<a:
        sm+=a-x
        b-=1
        i+=1
      else:
        i2+=1
        break

  print(sm)

main()


### FIXED CODE ###

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

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

def LI(): return list(map(int,input().split()))
def II(): return int(input())
def LS(): return input().split()
def S(): return input()

def main():
  n,m=LI()
  l=LI()

  l.sort()
  sm=sum(l)

  l3=[]
  for i in range(m):
    a,b=LI()
    l3.append([b,a])
  l3=sorted(l3,key=lambda x:x[0],reverse=True)

  n2=0
  for x in l3:
    n2+=x[1]

  # if n>n2:
  i=0
  i2=0
  while True:
    if i>n-1:
      break
    if i2>m-1:
      break

    a,b=l3[i2]
    while True:
      if i>n-1:
        break
      if i2>m-1:
        break

      if b==0:
        i2+=1
        break

      x=l[i]
      if x<a:
        sm+=a-x
        b-=1
        i+=1
      else:
        i2+=1
        break

  print(sm)

main()
### BUGGY CODE ###

N, W = map(int, input().split())
wv = [list(map(int, input().split())) for _ in range(N)]
ws = [x[0] for x in wv]
vs = [x[1] for x in wv]

dp = [{} for _ in range(100)]
def dfs(weight=0, depth=N - 1):
    if dp[depth].get(weight) is not None:
        return dp[depth][weight]

    if depth == -1:
        dp[depth][weight] = 0
        return 0

    if weight + ws[depth] <= W:
        result = max(dfs(weight, depth - 1), dfs(weight + ws[depth], depth - 1) + vs[depth])
    else:
        result = dfs(weight, depth - 1)
    dp[depth][weight] = result
    return result

print(dfs())


### FIXED CODE ###

N, W = map(int, input().split())
wv = [list(map(int, input().split())) for _ in range(N)]
ws = [x[0] for x in wv]
vs = [x[1] for x in wv]

dp = [[None] * (10**5 + 1) for _ in range(100 + 1)]
# def dfs(weight=0, depth=N - 1):
#     if dp[depth][weight] is not None:
#         return dp[depth][weight]
#
#     if depth == -1:
#         dp[depth][weight] = 0
#         return 0
#
#     if weight + ws[depth] <= W:
#         result = max(dfs(weight, depth - 1), dfs(weight + ws[depth], depth - 1) + vs[depth])
#     else:
#         result = dfs(weight, depth - 1)
#     dp[depth][weight] = result
#     return result
#
# print(dfs())

dp[-1] = [0] * len(dp[-1])
for depth in range(0, N):
    for weight in range(10**5 + 1):
        v = dp[depth - 1][weight]
        if weight + ws[depth] <= W:
            dp[depth][weight] = max(v, dp[depth - 1][weight + ws[depth]] + vs[depth])
        else:
            dp[depth][weight] = v

print(dp[N - 1][0])
### BUGGY CODE ###

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

max_a = max(A)

for i in reversed(range(max_a // 2 + 1)):
    # print(i)
    if(i in A):
        print(max_a, i)
        break
    elif((max_a - i) in A):
        print(max_a, max_a - i)
        break

### FIXED CODE ###

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

max_a = max(A)
s_set = set()
l_set = set()
for a in A:
    if(a <= max_a//2):
        s_set.add(a)
    else:
        l_set.add(a)

s_max = max(s_set | {0})
l_min = min(l_set | {max_a})

if(s_max >= (max_a - l_min)):
    print(max_a, s_max)
else:
    print(max_a, l_min)
### BUGGY CODE ###

N = int(input())
power = 1
for i in range(1,N+1):
    power *= i

power = power % (10**9+7)
print(power)

### FIXED CODE ###

N = int(input())
power = 1
C = 10**9+7
for i in range(1,N+1):
    power *= i
    power %= C

# power = power % (10**9+7)
print(power)
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10**6)

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

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

ans = [0 for i in range(n)]
for i in range(q) :
  p,x = map(int, input().split())
  p -= 1
  ans[p] += x

check = [0 for _ in range(n)]
def dfs(st) :
  check[st] = 1
  for ne in tree[st] :
    if check[ne] == 1 :
      continue
    ans[ne] += ans[st]
    dfs(ne)

dfs(0)

print(*ans)

### FIXED CODE ###

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

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

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

ans = [0 for i in range(n)]
for i in range(q) :
  p,x = map(int, input().split())
  p -= 1
  ans[p] += x

check = [0 for _ in range(n)]
def dfs(st) :
  check[st] = 1
  for ne in tree[st] :
    if check[ne] == 1 :
      continue
    ans[ne] += ans[st]
    dfs(ne)

dfs(0)

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

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

cnt = 0
while True:
    Flag = True
    for i in range(N):
        if a[i]%2 == 1 or not Flag:
            a[i] *= 3
        else:
            Flag = False
            a[i] //= 2
    if Flag:
        break
    else:
        cnt += 1
print(cnt)

### FIXED CODE ###

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

cnt = 0
for i in range(N):
    if a[i]%2 == 1:
        continue
    else:
        while True:
            if a[i]%2 == 1:
                break
            else:
                a[i] //= 2
                cnt += 1
print(cnt)
### BUGGY CODE ###

n,q=map(int,input().split())
s=input()
lr=[[0]*2 for i in range(q)]
for i in range(q):
    lr[i]=list(map(int,input().split()))
    
for lri in lr:
    print(s[lri[0]-1:lri[1]].count("AC"))
    

### FIXED CODE ###

n,q=map(int,input().split())
s=input()
cnt=[0]*n
icnt=0
for i in range(n-1):
#    print(s[i:i+2])
    if s[i:i+2]=="AC":
      icnt=icnt+1
      cnt[i+1]=cnt[i]+1
    else:
      cnt[i+1]=cnt[i]
#print(cnt,s)
for i in range(q):
    li,ri=map(int,input().split())
#    print(s[li-1:ri].count("AC"))
#    print(sum(cnt[li-1:ri-1]))
    print(cnt[ri-1]-cnt[li-1])
### BUGGY CODE ###

#ABC097  C
s = input()
k = int(input())

c = []
for i in range(len(s)+1):
	for j in range(i+1,len(s)+1):
		if s[i:j] not in c:
			c.append(s[i:j])
c.sort()
#print (c)
print (c[k-1])

### FIXED CODE ###

s = input()
k = int(input())

c = []
for i in range(1,6):
	for j in range(len(s)):
		if s[j:j+i] not in c:
			c.append(s[j:j+i])
c.sort()
print (c[k-1])
### BUGGY CODE ###

MOD = 1000000007

fact = [0 for i in range(100001)] # fact[i] = i! mod MOD
inv_fact = [0 for i in range(100001)] # inv_fact[i] = i!のmod MODでの逆元
 
# aのn乗をPで割った余りを求めるよ
def mod_pow(a, n, P):
	if n == 0: # aの0乗は1（それはそう）
		return 1
	if n%2 == 0: # aの4乗は（aの2乗）の2乗、みたいなノリ
		x = mod_pow(a, n/2, P)
		return (x*x)%P
	# aの5乗はa×（aの4乗）、みたいなノリ
	return (a*mod_pow(a, n-1, P))%P
 
# nCk mod MODを求める！！
def comb(n, k):
	if n < k:
		return 0
	ans = fact[n]
	ans = (ans * inv_fact[k])%MOD
	ans = (ans * inv_fact[n-k])%MOD
	return ans

def move(n):
	twonum = n // 2
	com = 0
	for i in range(twonum + 1):
		up = n - i
		com += comb(up, i)
	return com

# fact,inv_factを初期化
fact[0] = inv_fact[0] = 1
for i in range(100000):
	# (i+1)!ってi!に(i+1)をかけたものだよね
	fact[i+1] = (fact[i]*(i+1))%MOD
	# (i+1)!の逆元って、i!の逆元に(i+1)の逆元をかけたものだよね
	inv_fact[i+1] = (inv_fact[i]*mod_pow(i+1, MOD-2, MOD))%MOD

N, M = map(int, input().split())
a = []
a.append(0)
for i in range(M):
	a.append(int(input()))
a.append(N+1)

s = 1
for i in range(M+1):
	step = a[i+1] - a[i] - 1
	if step > MOD:
		step = step % MOD
	m = move(step)
	s = (s * m) % MOD
	a[i+1] += 1

print(s)


### FIXED CODE ###

MOD = 1000000007

fact = [0 for i in range(100001)] # fact[i] = i! mod MOD
inv_fact = [0 for i in range(100001)] # inv_fact[i] = i!のmod MODでの逆元
 
# aのn乗をPで割った余りを求めるよ
def mod_pow(a, n, P):
	if n == 0: # aの0乗は1（それはそう）
		return 1
	if n%2 == 0: # aの4乗は（aの2乗）の2乗、みたいなノリ
		x = mod_pow(a, n/2, P)
		return (x*x)%P
	# aの5乗はa×（aの4乗）、みたいなノリ
	return (a*mod_pow(a, n-1, P))%P
 
# nCk mod MODを求める！！
def comb(n, k):
	if n < k:
		return 0
	ans = fact[n]
	ans = (ans * inv_fact[k])%MOD
	ans = (ans * inv_fact[n-k])%MOD
	return ans

def move(n):
	twonum = n // 2
	com = 0
	for i in range(twonum + 1):
		up = n - i
		com += comb(up, i)
	return com

# fact,inv_factを初期化
fact[0] = inv_fact[0] = 1
for i in range(100000):
	# (i+1)!ってi!に(i+1)をかけたものだよね
	fact[i+1] = (fact[i]*(i+1))%MOD
	# (i+1)!の逆元って、i!の逆元に(i+1)の逆元をかけたものだよね
	inv_fact[i+1] = (inv_fact[i]*mod_pow(i+1, MOD-2, MOD))%MOD

N, M = map(int, input().split())
a = []
a.append(0)
for i in range(M):
	a.append(int(input()))
a.append(N+1)

s = 1
for i in range(M+1):
	step = a[i+1] - a[i] - 1
	if step > MOD:
		step = step % MOD
	m = move(step)
	s = (s * m) % MOD
	a[i+1] += 1

print(s)
### BUGGY CODE ###

import math

s = input()
K = int(input())

n=0
z=[]
while(n<len(s)):
    x=[]
    for i in range(len(s)-n):
        x.append(s[i:i+n+1])
    y = sorted(set(x))
    z += y[:K]
    n += 1

print(sorted(set(z))[K-1])

### FIXED CODE ###


import math

s = input()
K = int(input())

init = sorted(set(list(s)))[:K]
n=0
z=[]
while(n<len(s)):
    if n > 500: break
    x=[]
    for i in range(len(s)-n):
        if s[i] in init:
            x.append(s[i:i+n+1])
    y = sorted(set(x+z))
    z = y[:K]
    n += 1
print(sorted(set(z))[K-1])
### BUGGY CODE ###

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

    max1 = 0
    for x in range(1,N+1):
        tmp = int(A*x/B) - A*int(x/B)
        max1 = max(max1,tmp)
    print(max1)

main()


### FIXED CODE ###

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

    x = min(B-1,N)
    max1 = int(A*x/B) - A*int(x/B)
    print(max1)

main()
### BUGGY CODE ###

#coding:utf-8

n, k, q = map(int, input().split())
a = [input() for i in range(q)]
point = [k] * n
#print(point)

for i in range(0, q):
    point = [j-1 for j in point]
    point[int(a[i])-1] += 1
    #print(point)

for i in point:
    if i <= 0:
        print('No')
    else:
        print('Yes')

### FIXED CODE ###

#coding:utf-8

n, k, q = map(int, input().split())
a = [input() for i in range(q)]
point = [k-q] * n
#print(point)

for i in range(0, q):
    point[int(a[i])-1] += 1
    #print(point)

for i in point:
    if i <= 0:
        print('No')
    else:
        print('Yes')
### BUGGY CODE ###

N, K = map(int, input().split())
X = list(map(int, input().split()))
X.sort()
pY = []
mY = []
z = 0
for x in X:
    if x > 0:
        pY.append(x)
    elif x < 0:
        mY.append(x)
    else:
        z += 1

def bsearch(mn, mx, func):
    #func(i)=False を満たす最大のi
    idx = (mx + mn)//2
    while mx-mn>1:
        if func(idx):
            idx, mx = (idx + mn)//2, idx
            continue
        idx, mn = (idx + mx)//2, idx
    return idx


def count2(k):
    c = 0
    for y in pY:
        c += bsearch(-1, N, lambda i:X[i]*y>k) + 1
    for y in mY:
        c += N-(bsearch(-1, N, lambda i:X[i]*y<=k)+1)
    if k >= 0:
        c += N*z
    for x in X:
        if x*x <=k:
            c -= 1
    c = c//2
    return c


def count(k):
    # x*y <= k を満たすx,yの個数
    c = 0
    for i in range(N):
        for j in range(i+1, N):
            if X[i]*X[j] <= k:
                c += 1
    return c

x = bsearch(-10**18, 10**18, lambda x : count2(x)>=K)
print(x+1)


### FIXED CODE ###

N, K = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
mA, nA, zc = [], [], 0
dd = []
for a in A:
    if a<0:
        mA.append(a)
    elif a>0:
        nA.append(a)
    else:
        zc += 1
    dd.append(a*a)
#rA = A[::-1]
#print(mA, nA)
lnA = len(nA)
lmA = len(mA)

def F(idx):
    j = lnA-1
    r = 0
    for a in nA:
        while j >= 0:
            if nA[j]*a <= idx:
                break
            j -= 1
        r += j+1
    if idx >= 0:
#        print(2*(zc*N) - zc*zc)
        r += 2*(zc*N) - zc*zc
#    print(r, zc)
    j = 0
    for a in mA[::-1]:
        while j < lmA:
            if mA[j]*a <= idx:
                break
            j += 1
        r += lmA-j
    j = 0
    for a in mA:
        while j < lnA:
            if nA[j]*a <= idx:
                break
            j += 1
        r += 2*(lnA-j)

    for a in dd:
        if a <= idx:
            r-=1
    return r//2
#print(F(448283280358331064))

mx, mn = 2*10**18, -2*10**18
idx = (mx + mn)//2
target = K
while mx - mn > 1:
    if F(idx) < target:
        idx, mn = (idx + mx)//2, idx
        continue
    idx, mx = (idx + mn)//2, idx
print(idx+1)
### BUGGY CODE ###

# if the remainders (mod 2019) are equal, the difference will be divisible
# x = Q*2019+5 y = R*2019+5 then x-y=(Q-R)*2019
# unless Q-R<=0
# where the substring itself is (Q-R)*2019/10**(something)
# 2019 = 3*673 in prime factorization
# so multiplying by 10 doesn't affect whether a number is divisible by it
from collections import Counter
s = input()
partial = 0
remainders = list()
for i in range(len(s)-1, -1, -1):
  partial = (partial+int(s[i])*10**(len(s)-1-i))%2019
  remainders.append(partial)
histo = Counter(remainders)
non_single_count = int(sum(count*(count-1)/2 for value, count in histo.items() if value!=0))
single_count = int(sum(count for value, count in histo.items() if value==0))
print(non_single_count+single_count)

### FIXED CODE ###

# if the remainders (mod 2019) are equal, the difference will be divisible
# x = Q*2019+5 y = R*2019+5 then x-y=(Q-R)*2019
# unless Q-R<=0
# where the substring itself is (Q-R)*2019/10**(something)
from collections import Counter
s = input()[::-1]
partial = 0
remainders = list()
num = (int(character) for character in s)
for i, int_char in enumerate(num):
  partial = (partial+(int_char*pow(10,i,2019))%2019)%2019
  remainders.append(partial)
histo = Counter(remainders)
non_single_count = int(sum(count*(count-1)/2 for value, count in histo.items() if value!=0))
single_count = int(sum(count+count*(count-1)/2 for value, count in histo.items() if value==0))
print(non_single_count+single_count)
### BUGGY CODE ###

n = int(raw_input())
a = raw_input().split()

cnt = 0
for i in a:
    a[cnt] = int(i)
    cnt += 1

chk = {}
def make_divisors(k):
    divisors = []
    for i in range(1, int(k**0.5)+1):
        if k % i == 0:
            if i in chk:
                chk[i] += 1
            else:
                chk[i] = 1
            if i != k // i:
                key = int(k//i)
                if key in chk:
                    chk[key] += 1
                else:
                    chk[key] = 1
    return divisors

for i in range(2):
    make_divisors(a[i])
cnt = 1
for i in range(2,len(a)):
    k = a[i]
#    if k in chk:
#        continue
    del_list = []
    for j in chk:
        if k % j == 0:
            chk[j] += 1
        if chk[j] < cnt+1:
            del_list.append(j)
    for j in del_list:
        del chk[j]
    cnt += 1

answer = max(chk.keys())
#answer = 0
#for i in chk:
#    if int(chk[i]) >= chk[1] - 1 and i > answer:
#        answer = i
print answer

### FIXED CODE ###

n = int(raw_input())
a = raw_input().split()

cnt = 0
for i in a:
    a[cnt] = int(i)
    cnt += 1

chk = {}
chk2 = {}
def make_divisors(k):
    divisors = []
    for i in range(1, int(k**0.5)+1):
        if k % i == 0:
            if i in chk:
                chk[i] += 1
            else:
                chk[i] = 1
            if i != k // i:
                key = int(k//i)
                if key in chk:
                    chk[key] += 1
                else:
                    chk[key] = 1
    return divisors

for i in range(2):
    make_divisors(a[i])
cnt = 1
for i in range(2,len(a)):
    k = a[i]
    if k not in chk2:
        chk2[k] = 1
    else:
        if chk2[k] == 1:
            chk2[k] += 1
        elif chk2[k] > 1:
            continue
    del_list = []
    for j in chk:
        if k % j == 0:
            chk[j] += 1
        if chk[j] < cnt+1:
            del_list.append(j)
    for j in del_list:
        del chk[j]
    cnt += 1

answer = 0
for i in chk:
    if int(chk[i]) >= chk[1] - 1 and i > answer:
        answer = i
print answer
### BUGGY CODE ###

n=int(input())
arr=input()
prod=1
k=1;
l=list(map(int,arr.split(' ')))
for x in l:
    if(x==0):
        prod=0
        if(k==0):
            continue
    prod*=x
    if(prod>1000000000000000000):
        k=0
        prod=-1

    
print(prod)


### FIXED CODE ###

n=int(input())
arr=input()
prod=1
k=1;
l=list(map(int,arr.split(' ')))
#l.sort()

for x in l:
    if(x==0):
        k=0
        break

if(k==0):
    print(0)
else:
    for x in l:
        prod*=x
        if(prod>1000000000000000000):
            prod=-1
            break
    print(prod)
### BUGGY CODE ###

n, m = map(int, input().split())
a = [int(i) for i in input().split()]
for _ in range(m):
  a.sort()
  a[-1]//=2
print(sum(a))

### FIXED CODE ###

n, m = map(int, input().split())
a = [int(i) for i in input().split()]
a.sort(reverse=True)
while m>0:
  a[0]//=2
  for i in range(1, m):
    if i<n and a[i] >= a[0]:
      a[i]//=2
    else:
      a.sort(reverse=True)
      m-=i
      break
  else:
    break
print(sum(a))
### BUGGY CODE ###

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

AB.sort(reverse=True)
dp = [0] * (T + 1)

for a, b in AB:
    for t in range(T):
        x = dp[t+a]+b if t+a < T else b
        dp[t] = max(dp[t], x)

ans = dp[0]
print(ans)


### FIXED CODE ###

import numpy as np
N, T = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(N)]


def knapsack(ab):
    dp = np.zeros(T, dtype=np.int64)
    res = [dp]
    for a, b in ab:
        newDP = res[-1].copy()
        newDP[a:] = np.maximum(newDP[a:], newDP[:-a] + b)
        res.append(newDP)
    return res


dp1 = knapsack(AB)
dp2 = knapsack(AB[::-1])
dp2 = dp2[::-1]

ans = 0

for i in range(N):
    _, b = AB[i]
    l = dp1[i]
    r = dp2[i + 1][::-1]
    tmp = (l + r).max() + b
    ans = max(ans, tmp)
print(ans)
### BUGGY CODE ###

N,Q = map(int,input().split())
S = input()
L = [list(map(int,input().split())) for i in range(Q)]

for left,right in L :
    left -= 1
    ans = S[left:right].count("AC")
    print(ans)



### FIXED CODE ###

N,Q = map(int,input().split())
S = input()
L = [list(map(int,input().split())) for i in range(Q)]

loc = [0 for i in range(N+1)]
for i in range(N) :
    if S[i:i+2] == "AC" :
        loc[i+1] = loc[i]+1
    else :
        loc[i+1] = loc[i]
for l,r in L :
    l -= 1
    r -= 1
    ans = loc[r] - loc[l]
    print(ans)
### BUGGY CODE ###

from collections import defaultdict,deque
class dfs:
    def __init__(self,n,a,b,c,d):
        self.N = n
        self.A = a
        self.B = b
        self.C = c
        self.D = d
        self.ans = self.N * self.D
        self.memory = defaultdict(int)
        self.Q = deque([[self.N,0]])
    def dfs(self):
        while self.Q:
            num,cost = self.Q.popleft()
            if self.memory[num] > cost :
                pass
            else:
                if num == 0:
                    self.ans = min(self.ans,cost)
                elif num == 1:
                    self.ans = min(self.ans,cost+self.D)
                else:
                    for step,a_cost in [[2,self.A],[3,self.B],[5,self.C]]:
                        if num % step != 0:
                            temp_num = (num//step)+1
                            temp_cost = cost + (((num//step)+1)*step - num) * self.D + a_cost
                            self.memo_check_append(temp_num,temp_cost)
                        temp_num = num//step
                        temp_cost = cost + (num - (num//step)*step) * self.D + a_cost
                        self.memo_check_append(temp_num,temp_cost)
                    self.ans = min(self.ans,cost + num * self.D)
        return self.ans
    def memo_check_append(self,n,c):
        if self.memory[n] > c or self.memory[n] == 0:
            self.Q.append([n,c])
            self.memory[n] = c

N = int(input())
for _ in range(N):
  N,A,B,C,D = map(int,input().split())
  T = dfs(N,A,B,C,D)
  print(T.dfs())

### FIXED CODE ###

from collections import defaultdict,deque
class dfs:
    def __init__(self,n,a,b,c,d):
        self.N = n
        self.A = a
        self.B = b
        self.C = c
        self.D = d
        self.ans = self.N * self.D
        self.memory = defaultdict(int)
        self.Q = deque([[self.N,0]])
    def dfs(self):
        while self.Q:
            num,cost = self.Q.popleft()
            if self.memory[num] > cost :
                pass
            else:
                if num == 0:
                    self.ans = min(self.ans,cost)
                elif num == 1:
                    self.ans = min(self.ans,cost+self.D)
                else:
                    for step,a_cost in [[2,self.A],[3,self.B],[5,self.C]]:
                        if num % step != 0:
                            temp_num = (num//step)+1
                            temp_cost = cost + (((num//step)+1)*step - num) * self.D + a_cost
                            self.memo_check_append(temp_num,temp_cost)
                        temp_num = num//step
                        temp_cost = cost + (num - (num//step)*step) * self.D + a_cost
                        self.memo_check_append(temp_num,temp_cost)
                    self.ans = min(self.ans,cost + num * self.D)
        return self.ans
    def memo_check_append(self,n,c):
        if self.memory[n] > c or self.memory[n] == 0:
            self.Q.append([n,c])
            self.memory[n] = c

N = int(input())
for _ in range(N):
  N,A,B,C,D = map(int,input().split())
  T = dfs(N,A,B,C,D)
  print(T.dfs())
### BUGGY CODE ###

#!/usr/bin/env python3

def main():
    na = list(map(int, input().split()))
    N, C = na[0], na[1]

    D = []
    for i in range(C):
        D.append(list(map(int, input().split())))
    c = []
    for i in range(N):
        c.append(list(map(int, input().split())))

    s = []
    s.append([0] * (C + 1))
    s.append([0] * (C + 1))
    s.append([0] * (C + 1))

    for i in range(N):
        for j in range(N):
            for k in range(1, C + 1):
                s[(i + j) % 3][k] += D[c[i][j] -1][k - 1]

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


    print(s_min)


if __name__ == '__main__':
    main()



### FIXED CODE ###

#!/usr/bin/env python3

def main():
    na = list(map(int, input().split()))
    N, C = na[0], na[1]

    D = []
    for i in range(C):
        D.append(list(map(int, input().split())))
    c = []
    for i in range(N):
        c.append(list(map(int, input().split())))

    s = []
    s.append([0] * (C + 1))
    s.append([0] * (C + 1))
    s.append([0] * (C + 1))

    for i in range(N):
        for j in range(N):
            m = (i + j) % 3
            for k in range(1, C + 1):
                s[m][k] += D[c[i][j] -1][k - 1]

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


    print(s_min)


if __name__ == '__main__':
    main()