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

N, K = map(int, input().split())
nums = [[] for i in range(N)]
for i in range(N):
    t, d = map(int, input().split())
    t -= 1
    nums[t].append(d)
maxs = []
rest = []
for i in range(N):
    nums[i].sort(reverse=True)
    if len(nums[i]) > 0:
        maxs.append(nums[i][0])
        rest = rest + nums[i][1:]
maxs.sort(reverse=True)
if len(maxs) > K:
    maxs = maxs[:K]
    rest = rest + maxs[K:]
rest.sort(reverse=True)
other = []
idx = 0
while len(maxs)+len(other) < K:
    other.append(rest[idx])
    idx += 1
rest = rest[idx:]

types = len(maxs)
#print(maxs)
#print(rest)
for i,r in enumerate(rest):
    diff = types*types - pow(types-1, 2)
    if diff < r-maxs[len(maxs)-1-i]:
        maxs[len(maxs)-1-i] = r
        types -= 1
    else:
        break
ans = types*types
for num in (maxs+other):
    ans += num
print(ans)


### FIXED CODE ###

N, K = map(int, input().split())
nums = [[] for i in range(N)]
for i in range(N):
    t, d = map(int, input().split())
    t -= 1
    nums[t].append(d)
maxs = []
rest = []
for i in range(N):
    nums[i].sort(reverse=True)
    if len(nums[i]) > 0:
        maxs.append(nums[i][0])
        for n in nums[i][1:]:
            rest.append(n)
        #rest = rest + nums[i][1:]
maxs.sort(reverse=True)
if len(maxs) > K:
    maxs = maxs[:K]
    for n in maxs[K:]:
        rest.append(n)
    #rest = rest + maxs[K:]
rest.sort(reverse=True)
other = []
idx = 0
while len(maxs)+len(other) < K:
    other.append(rest[idx])
    idx += 1
rest = rest[idx:]

types = len(maxs)
#print(maxs)
#print(rest)
for i,r in enumerate(rest):
    diff = types*types - pow(types-1, 2)
    if diff < r-maxs[len(maxs)-1-i]:
        maxs[len(maxs)-1-i] = r
        types -= 1
    else:
        break
ans = types*types
for num in maxs:
    ans += num
for num in other:
    ans += num
print(ans)
### BUGGY CODE ###

import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


xs,ys,xt,yt = list(map(int, input().split()))
n = int(input())
xyr = [None]*(n+2)
for i in range(n):
    xyr[i] = tuple(map(int, input().split()))
from itertools import product
ns = [[] for _ in range(n+2)]
s = n
t = n+1
xyr[s] = (xs,ys,0)
xyr[t] = (xt,yt,0)
for i,j in product(range(n+2), range(n+2)):
    if i!=j:
        d = max(0, ((xyr[i][0]-xyr[j][0])**2 + (xyr[i][1]-xyr[j][1])**2)**0.5 - (xyr[i][2]+xyr[j][2]))
        ns[i].append((d,j))
        ns[j].append((d,i))
def dijkstra(start):
    import heapq
    vals = [None] * (n+2)
    h = [(0, start)] # (距離, ノード番号)
    vals[start] = 0
    while h:
        val, u = heapq.heappop(h)
        if u==t:
            break
        for d, v in ns[u]:
            if vals[v] is None or vals[v]>val+d:
                vals[v] = val+d
                heapq.heappush(h, (vals[v], v))
    return vals
vals = dijkstra(s)
ans = vals[t]
print(ans)

### FIXED CODE ###

import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


xs,ys,xt,yt = list(map(int, input().split()))
n = int(input())
xyr = [None]*(n+2)
for i in range(n):
    xyr[i] = tuple(map(int, input().split()))
from itertools import product
# ns = [[] for _ in range(n+2)]
data = []
rs = []
cs = []
s = n
t = n+1
xyr[s] = (xs,ys,0)
xyr[t] = (xt,yt,0)
for i,j in product(range(n+2), range(n+2)):
    if i<j:
        d = max(0, ((xyr[i][0]-xyr[j][0])**2 + (xyr[i][1]-xyr[j][1])**2)**0.5 - (xyr[i][2]+xyr[j][2]))
        data.append(d)
        rs.append(i)
        cs.append(j)
import scipy.sparse
m = scipy.sparse.csr_matrix((data, (rs, cs)), shape=(n+2, n+2))
ans = scipy.sparse.csgraph.dijkstra(m, indices=t, directed=False)
print(ans[s])
### BUGGY CODE ###

def s(n):
	sum = 0
	for c in str(n):
		sum += int(c)
	return sum

def isSunuke(n):
	for m in range(n+1, n * 10):
		if (n / s(n)) > (m / s(m)):
			return False
	return True

k = int(input())
found=0
n = 1
while(found < k):
	if isSunuke(n):
		print(n)
		found+=1
	n += 1

### FIXED CODE ###

import math
# import datetime

def s(n):
	sum = 0
	for c in str(n):
		sum += int(c)
	return sum

k = int(input())
found=0

def next_sunuke(n, s_n, s_n_div):

	global found

	if n == 1:
		return

	log_n = int(math.log(n,10))
	m = n - 10 ** int(log_n // 1.25)
	# m = n - 1

	while m >= 1:
		s_m = s(m)
		s_mplus1 = s(m + 1)

		# if (s_m < s_mplus1 or (s_n - s_m != 1 and s_n - s_m != -8)) and m > 9:
		if (s_m < s_mplus1) and m > 9:
			m -= 10 ** int(log_n // 1.25)
			continue

		# print("check: " + str(m))

		s_m_div = m / s(m)

		if s_m_div <= s_n_div:
			next_sunuke(m, s_m, s_m_div)
			if found >= k:
				return

			found += 1
			# print("{0:d}".format(m), "{0:+d}".format(n-m), "{0:d}".format(s_m), s_m_div)
			print(m)
			break
		# else:
		# 	log_m = int(math.log(m,10))
		# 	if (m + 1) / (10 ** (log_m - 1)) == 19:

		# 		print ("skip: " + str(m) + " to " + str(10 ** log_m - 1))

		# 		m = 10 ** log_m - 1
		# 		s_mplus1 = s(m+1)
		# 		continue

		m -= 10 ** int(log_n // 1.25)


# 適当な大きいスヌケ数
current_sunuke = 999999999999999
s_current_sunuke = s(current_sunuke)
s_current_sunuke_div = current_sunuke / s_current_sunuke

# start = datetime.datetime.now()
next_sunuke(current_sunuke, s_current_sunuke, s_current_sunuke_div)
if found < k:
	print(current_sunuke)
# end = datetime.datetime.now()
# print(str(end-start))

# sunukes=[]

# n = current_sunuke - 1

# while(n >= 1):
# 	s_n = n / s(n)
# 	if s_n <= current_sunuke_n:
# 		#sunukes.insert(0,n)
# 		sunukes.append(n)
# 		current_sunuke = n
# 		current_sunuke_n = s_n
# 	n -= 1

# for n in sunukes:
# 	print (n)
### BUGGY CODE ###

N = int(input())

c = 0
for i in range(357, N + 1):
	if (set(str(i)) == {"3", "5", "7"}):
		c += 1
print(c)


### FIXED CODE ###

S = input()

def solve(s, n=0, tight=True, value=""):
	if n == len(s):
		while value and value[0] == "0":
			value = value[1:]
		if set("753") == set(value):
			#print(value)
			return 1
		return 0
	hi = int(s[n]) if tight else 9
	c = 0
	for i in range(hi + 1):
		if i in [7, 5, 3, 0]:
			c += solve(s, n + 1, tight and not(i < hi), value + str(i))
	return c

print(solve(S))
### BUGGY CODE ###

n = int(input())
vals = list(map(lambda v: int(v), input().split()))
i = 0
sum = 1

while (i < len(vals)):
  sum = sum * vals[i]
  i = i + 1

if (sum > 10e17):
  print(-1)
  exit()

print(sum)

### FIXED CODE ###

n = int(input())
vals = list(map(lambda v: int(v), input().split()))
vals.sort(reverse=True)
i = 0
sum = 1

if (0 in vals):
  print(0)
  exit()

while (i < len(vals)):
  sum = sum * vals[i]
  if (sum > 10e17):
    print(-1)
    exit()
  i = i + 1

print(sum)
### BUGGY CODE ###

#!/usr/bin/env python3
import sys


def solve(N: int, A: "List[int]"):
    switch_count = N if N%2 == 0 else N-1
    A.sort()
    sumA = sum(A)
    answer = 0
    for i in range(0,switch_count+1,2):
        a = sumA
        a += sum([-j for j in A[:i]])*2
        answer = max(a,answer)
    print(answer)

    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, A)

if __name__ == '__main__':
    main()


### FIXED CODE ###

#!/usr/bin/env python3
import sys


def solve(N: int, A: "List[int]"):
    switch_count = N if N%2 == 0 else N-1
    A.sort()
    sumA = sum(A)
    answer = sumA
    prev = sumA
    for i in range(2,switch_count+1,2):
        a = prev - A[i-1]*2 - A[i-2]*2
        answer = max(a,answer)
        prev = a
    print(answer)

    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, A)

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

import bisect

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

for _ in range(M):
    B, C = map(int, input().split())
    i = bisect.bisect_right(A, C)
    if N <= i:
        A = A[B:i] + [C] * B + A[i:]
    elif i <= B:
        A[:i] = [C] * i
    else:
        A = A[B:i] + [C] * B + A[i:]
print(sum(A))

### FIXED CODE ###

N, M = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
BC = []
for _ in range(M):
    B, C = map(int, input().split())
    BC.append((B, C))
BC.sort(key=lambda bc: (bc[1], bc[0]), reverse=True)

ai = 0
bci = bcj = 0
while ai < N and bci < M:
    if A[ai] < BC[bci][1]:
        A[ai] = BC[bci][1]
        ai += 1
        bcj += 1
        if BC[bci][0] <= bcj:
            bci += 1
            bcj = 0
    else:
        ai += 1
print(sum(A))
### BUGGY CODE ###

N = int(input())
import sys
sys.setrecursionlimit(1000000)
MOD = 10**9+7
E = {}
for i in range(0,N+1):
    E[i] = []
for i in range(N-1):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    E[a].append(b)
    E[b].append(a)

dp = [ [0 for i in range(2)] for j in range(100100)]

def dfs(c,p):
    dp[c][0],dp[c][1] = 1,1
    for to in E[c]:
        if to != p:
            dfs(to,c)
            dp[c][0] *= (dp[to][0] + dp[to][1])%MOD
            dp[c][1] *= (dp[to][0])%MOD

dfs(0,-1)

ans = (dp[0][0] + dp[0][1]) % MOD
print(ans)


### FIXED CODE ###

from heapq import heappush, heappop
import collections
import math
import heapq
from collections import defaultdict
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
inf = float("inf")


def main():
    N = int(input())
    E = {}
    for i in range(0, N+1):
        E[i] = []
    for i in range(N-1):
        a, b = map(int, input().split())
        a -= 1
        b -= 1
        E[a].append(b)
        E[b].append(a)

    dp = [[0 for i in range(2)] for j in range(100100)]

    def dfs(c, p):
        dp[c][0], dp[c][1] = 1, 1
        for to in E[c]:
            if to != p:
                dfs(to, c)
                dp[c][0] *= dp[to][0] + dp[to][1]
                dp[c][1] *= dp[to][0]

    dfs(0, -1)

    ans = (dp[0][0] + dp[0][1]) % MOD
    print(ans)


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

s = input()
q = int(input())
for _ in range(q):
    t = input().split()
    if int(t[0]) == 1:
        s = s[::-1]
    else:
        if int(t[1]) == 1:
            s = t[2] + s
        else:
            s += t[2]
print(s)

### FIXED CODE ###

from collections import deque
s = deque(input())
num = int(input())
cnt = 0
for _ in range(num):
    t = input().split()
    if t[0] == "1":
        cnt += 1
    else:
        if (int(t[1])+cnt) % 2 == 1:
            s.appendleft(t[2])
        else:
            s.append(t[2])
if cnt % 2 == 1:
    s.reverse()
print("".join(s))
### BUGGY CODE ###

n, q = map(int, input().split())
s = str(input())
lr = []
for i in range(q):
    lr.append(list(input().split()))

for i in range(q):
    cnt = 0
    start = int(lr[i][0])
    end = int(lr[i][1])

    if end+1 < len(s):
        cnt = s[start-1:end].count('AC')
    else:
        cnt = s[start-1:end].count('AC')

    print(cnt)


### FIXED CODE ###

n, q = map(int, input().split())
s = str(input())
lr = []
for i in range(q):
    lr.append(list(input().split()))

n = len(s)
ary = [0 for i in range(len(s)+1)]

for i in range(1, n):
    if s[i-1] == 'A' and s[i] == 'C':
        ary[i+1] = ary[i] + 1
    else:
        ary[i+1] = ary[i]

for i in range(q):
    ans = ary[int(lr[i][1])] - ary[int(lr[i][0])]
    print(ans)
### BUGGY CODE ###

#!/usr/bin/env python3

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

    INF = 1 << 60
    dp = [INF] * 100010

    dp[0] = 0

    for i in range(N):
        for j in range(1, K + 1):
            if i + j < N:
                dp[i + j] = min(dp[i + j], dp[i] + abs(h[i] - h[i + j]))

    print(dp[N - 1])


if __name__ == "__main__":
    main()


### FIXED CODE ###

#!/usr/bin/env python3

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

    INF = 1 << 60
    dp = [INF] * 100010

    dp[0] = 0

    for i in range(N):
        for j in range(1, K + 1):
            if i + j < N:
                dp[i + j] = min(dp[i + j], dp[i] + abs(h[i] - h[i + j]))

    print(dp[N - 1])


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

from heapq import heapify, heappush, heappop
import sys
input = sys.stdin.readline

def solve():
    N, Q = map(int, input().split())
    events = []
    for i in range(N):
        S, T, X = map(int, input().split())
        events.append((S-X-0.5, 1, X))
        events.append((T-X-0.5, 0, X))
    for i in range(Q):
        D = int(input())
        events.append((D, 2, i))

    events.sort()

    anss = [-1] * Q
    PQ = []
    isClosed = dict()
    for tm, tp, x in events:
        if tp == 0:
            isClosed[x] = 0
        elif tp == 1:
            isClosed[x] = 1
            heappush(PQ, x)
        else:
            while PQ:
                if isClosed[PQ[0]] == 1:
                    anss[x] = PQ[0]
                    break
                heappop(PQ)

    print('\n'.join(map(str, anss)))


solve()


### FIXED CODE ###

from heapq import heapify, heappush, heappop
import sys
input = sys.stdin.readline

N, Q = map(int, input().split())
events = []
for iR in range(N):
    S, T, X = map(int, input().split())
    events.append((S-X, T-X, X))
events.sort()

iE = 0
anss = []
PQ = []
for _ in range(Q):
    D = int(input())
    while iE < N and events[iE][0] <= D:
        tmSt, tmEn, x = events[iE]
        heappush(PQ, (x, tmEn))
        iE += 1

    xMin = -1
    while PQ:
        x, tmEn = heappop(PQ)
        if tmEn > D:
            xMin = x
            heappush(PQ, (x, tmEn))
            break
    anss.append(xMin)

print('\n'.join(map(str, anss)))
### BUGGY CODE ###

N = int(input())
a = list(map(int,input().split()))
b = 1
for i in a:
    if b in a:
        if b == i:
            b += 1
    else:
        break
if b == 1:
    print(-1)
else:
    print(N-b+1)

### FIXED CODE ###

N = int(input())
a = list(map(int,input().split()))
b = 1
for i in range(N):
    if b == a[i]:
        b += 1
if b == 1:
    print(-1)
else:
    print(N-b+1)
### BUGGY CODE ###

import math
from functools import reduce

def gcd(*numbers):
    return reduce(math.gcd, numbers)

K = int(input())
ans = 0

for i in range(1, K+1):
    for j in range(1, K+1):
        for k in range(1, K+1):
            ans = ans + gcd(i,j,k)

print(ans)

### FIXED CODE ###

import math
from functools import reduce

def gcd(*numbers):
    return reduce(math.gcd, numbers)

K = int(input())
ans = 0

for i in range(1, K+1):
    for j in range(i, K+1):
        for k in range(j, K+1):
            #print(i,j,k)
            if i == j == k:
                ans = ans + gcd(i,j,k)
            elif i == j or j == k or i == k:
                ans = ans + gcd(i,j,k)*3
            else:
                ans = ans + gcd(i,j,k)*6

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

from collections import deque

N = int(input())
G = [deque() for _ in range(N)]
E = dict() # (a, b) -> [idx, color]
for i in range(N-1):
    a, b = map(lambda x: int(x)-1, input().split())
    G[a].append(b)
    E[(a, b)] = [i, 0]
    

K = 0
new_color = [i for i in range(N-1, 0, -1)]
used_color = set()
queue = deque()
node2colors = [set() for _ in range(N)]
def bfs(v):
    global K
    # seen[v] = 1
    queue.append(v)
    while queue:
        q = queue.popleft()
        # if seen[q]:
            # continue
        while G[q]:
            nex = G[q].popleft()
            dif = used_color.difference(node2colors[q])
            if dif:
                usd_c = dif.pop()
                dif.add(usd_c)
                E[(q, nex)][1] = usd_c
                node2colors[q].add(usd_c)
                node2colors[nex].add(usd_c)
            else:
                new_c = new_color.pop()
                E[(q, nex)][1] = new_c
                node2colors[q].add(new_c)
                node2colors[nex].add(new_c)
                used_color.add(new_c)
                K += 1
            queue.append(nex)

bfs(0)
ans_list = [value for value in E.values()]
print(K)
for i in range(N-1):
    print(ans_list[i][1])

### FIXED CODE ###

from collections import deque
import sys
input = sys.stdin.readline
    
def bfs(v, N, G, E):
    visited = [0]*N
    queue = deque()
    K = -1
    node2color = [-1 for _ in range(N)]
    queue.append(v)
    visited[v] = 1
    while queue:
        q = queue.popleft()
        color = 0
        for nex in G[q]:
            if visited[nex]:
                continue
            visited[nex] = 1
            color += 1
            if color == node2color[q]:
                color += 1
            
            node2color[nex] = color
            E[(min(q, nex), max(q, nex))] = color
            queue.append(nex)
        K = max(K, color)
    return K

def main():
    N = int(input())
    G = [deque() for _ in range(N)]
    E = dict() # (a, b) -> [idx, color]
    for i in range(N-1):
        a, b = map(lambda x: int(x)-1, input().split())
        G[a].append(b)
        G[b].append(a)
        E[(a, b)] = 0
    K = bfs(0, N, G, E)
    # ans_list = [value for value in E.values()]
    print(K)
    for value in E.values():
        print(value)
main()
### BUGGY CODE ###

n, m = map(int, input().split())
jobs = []

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

jobs_sorted = sorted(jobs, key=lambda x:(x[0],-x[1]))

days = [0 for i in range(m + 1)]
for i in range(n):
    # print(jobs_sorted[i])
    if jobs_sorted[i][0] <= m:
        for j in range(m - jobs_sorted[i][0], -1, -1):
            if days[j] < jobs_sorted[i][1]:
                for k in range(0, j):
                    if days[k+1] != 0:
                        days[k] = days[k+1]
                days[j] = jobs_sorted[i][1]
                break
    # print(days)

print(sum(days))

### FIXED CODE ###

import heapq

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

for i in range(n):
    a, b = map(int, input().split())
    if not a in jobs.keys():
        jobs[a] = [-b]
    else:
        jobs[a].append(-b)
# print(jobs)
sum_money = 0
money_list = [0]
heapq.heapify(money_list)
for i in range(1, m+1):
    if i in jobs.keys():
        for money in jobs[i]:
            heapq.heappush(money_list, money)
    # print(money_list)
    max_money = -heapq.heappop(money_list)
    sum_money += max_money
    if max_money == 0:
        heapq.heappush(money_list, 0)
print(sum_money)
### BUGGY CODE ###

N,H = map(int,input().split())
A = []
B = []
for i in range(N):
    a,b = map(int,input().split())
    A.append(a)
    B.append(b)
C = 0
while H > 0:
    C += 1
    Ma = max(A)
    if B == []:
        H -= Ma
    else:
        Mb = max(B)
        if Ma > Mb:
            H -= Ma
        else:
            H -= Mb
            B.remove(Mb)
print(C)

### FIXED CODE ###

N,H = map(int,input().split())
Ma = 1
B = []
for i in range(N):
    a,b = map(int,input().split())
    B.append(b)
    if a > Ma:
        Ma = a
B.sort()
B.reverse()
i = 0
Mb = B[0]
while Mb > Ma and H > 0:
  i += 1
  H -= Mb
  if i == N:
    Mb = 0
  else:
    Mb = B[i]
if H <= 0:
  print(i)
else:
  print(i+int(-(-H//Ma)))
### BUGGY CODE ###

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

ans = 0
for i in range(1, N):
    S1 = S[:i]
    S2 = S[i:]
    ok = 0
    ng = len(S2) + 1
    k = (ok + ng) // 2
    while ng - ok > 1:
        if S1.count(S2[:k]) > 0:
            ok = k
            k = (k + ng) // 2
        else:
            ng = k
            k = (k + ok) // 2
        if k == 0:
            break
    ans = max(ans, k)
print(ans)


### FIXED CODE ###

from collections import defaultdict

N = int(input())
S = input()
mod1 = 10 ** 9 + 7
mod2 = 10 ** 9 + 9
base1 = 1007
base2 = 2009

ok = 0
ng = N // 2 + 1
mid = (ok + ng) // 2
while ng - ok > 1:
    seen1 = defaultdict(lambda: 10 ** 5)
    seen2 = defaultdict(lambda: 10 ** 5)
    rh1 = 0
    rh2 = 0
    for i in range(mid):
        rh1 += ord(S[i]) * pow(base1, mid - i - 1, mod1)
        rh2 += ord(S[i]) * pow(base2, mid - i - 1, mod2)
        rh1 %= mod1
        rh2 %= mod2
    seen1[rh1] = 0
    seen2[rh2] = 0
    flag = 0
    for i in range(1, N - mid + 1):
        if flag == 1:
            break
        rh1 = (rh1 * base1 + ord(S[i + mid - 1]) - ord(S[i - 1]) * pow(base1, mid, mod1)) % mod1
        rh2 = (rh2 * base2 + ord(S[i + mid - 1]) - ord(S[i - 1]) * pow(base2, mid, mod2)) % mod2
        if i - seen1[rh1] >= mid and i - seen2[rh2] >= mid:
            ok = mid
            mid = (ok + ng) // 2
            flag = 1
        else:
            if seen1[rh1] == 10 ** 5:
                seen1[rh1] = i
            if seen2[rh2] == 10 ** 5:
                seen2[rh2] = i
    if flag == 0:
        ng = mid
        mid = (ok + ng) // 2

print(ok)
### BUGGY CODE ###

# https://qiita.com/_-_-_-_-_/items/34f933adc7be875e61d0
# abcde	s=input()	s='abcde'
# abcde	s=list(input())	s=['a', 'b', 'c', 'd', 'e']
# 5(1つだけ)	a=int(input())	a=5
# 1 2	| x,y = s_inpl()   |	x=1,y=2
# 1 2 3 4 5 ... n 　	li = input().split()	li=['1','2','3',...,'n']
# 1 2 3 4 5 ... n 　	li = inpl()	li=[1,2,3,4,5,...,n]
# FFFTFTTFF 　	li = input().split('T')	li=['FFF', 'F', '', 'FF']

# INPUT
# 3
# hoge
# foo
# bar
# ANSWER
# n=int(input())
# string_list=[input() for i in range(n)]

import math
import copy
from collections import defaultdict, Counter
# 直積 A={a, b, c}, B={d, e}:のとき，A×B={(a,d),(a,e),(b,d),(b,e),(c,d),(c,e)}: product(A, B)
from itertools import product
# 階乗 P!: permutations(seq), 順列 {}_len(seq) P_n: permutations(seq, n)
from itertools import permutations
# 組み合わせ {}_len(seq) C_n: combinations(seq, n)
from itertools import combinations
from bisect import bisect_left, bisect_right
import numpy as np

def i_inpl(): return int(input())
def s_inpl(): return map(int,input().split())
def l_inpl(): return list(map(int, input().split()))
INF = float("inf")

N = i_inpl()
F = []
for _ in range(N):
    Fi = l_inpl()
    F.append(Fi)

P = []
for _ in range(N):
    Pi = l_inpl()
    P.append(Pi)


# bit全探索
ans = -1 * INF
for row in product([0, 1], repeat=10):
    tmp = 0
    open_num = 0
    for ind, Fi in enumerate(F):
        open_num += np.logical_and(np.array(row), np.array(Fi)).sum()
        tmp += P[ind][np.logical_and(np.array(row), np.array(Fi)).sum()]
    if tmp > ans and open_num>0:
        ans = tmp

print(ans)

### FIXED CODE ###

# https://qiita.com/_-_-_-_-_/items/34f933adc7be875e61d0
# abcde	s=input()	s='abcde'
# abcde	s=list(input())	s=['a', 'b', 'c', 'd', 'e']
# 5(1つだけ)	a=int(input())	a=5
# 1 2	| x,y = s_inpl()   |	x=1,y=2
# 1 2 3 4 5 ... n 　	li = input().split()	li=['1','2','3',...,'n']
# 1 2 3 4 5 ... n 　	li = inpl()	li=[1,2,3,4,5,...,n]
# FFFTFTTFF 　	li = input().split('T')	li=['FFF', 'F', '', 'FF']

# INPUT
# 3
# hoge
# foo
# bar
# ANSWER
# n=int(input())
# string_list=[input() for i in range(n)]

import math
import copy
from collections import defaultdict, Counter
# 直積 A={a, b, c}, B={d, e}:のとき，A×B={(a,d),(a,e),(b,d),(b,e),(c,d),(c,e)}: product(A, B)
from itertools import product
# 階乗 P!: permutations(seq), 順列 {}_len(seq) P_n: permutations(seq, n)
from itertools import permutations
# 組み合わせ {}_len(seq) C_n: combinations(seq, n)
from itertools import combinations
from bisect import bisect_left, bisect_right
# import numpy as np

def i_inpl(): return int(input())
def s_inpl(): return map(int,input().split())
def l_inpl(): return list(map(int, input().split()))
INF = float("inf")

N = i_inpl()
F = []
for _ in range(N):
    Fi = l_inpl()
    F.append(Fi)

P = []
for _ in range(N):
    Pi = l_inpl()
    P.append(Pi)


# bit全探索
ans = -1 * INF
for i in range(1, 2**10):
    tmp = 0
    for j in range(N):
        c = 0
        # NOTE: iとF[j]のAND演算
        for k in range(10):
            if ((i>>k) & 1) & F[j][k]:
                c += 1
        tmp += P[j][c]
    ans = max(ans, tmp)

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

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

output='Yes'
for i in range(n-1):
  if h[i]-h[i+1]>0:
    if h[i]-min(h[i:])>1:
      output='No'
      
print(output)

### FIXED CODE ###

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

index=N-1
output='Yes'
while index>0:
  if h[index-1]-h[index]>1:
    output='No'
    break
  elif h[index-1]-h[index]==1:
    h[index-1]-=1
  else:
    pass
  index-=1
  
print(output)