Problem:


Score: 500 points

Problem Statement

Takahashi will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i.

In the contest, N foods numbered 1 through N will be presented, and the difficulty of Food i is F_i. The details of the contest are as follows:

A team should assign one member to each food, and should not assign the same member to multiple foods.

It will take x \times y seconds for a member to finish the food, where x is the consumption coefficient of the member and y is the difficulty of the dish.

The score of a team is the longest time it takes for an individual member to finish the food.

Before the contest, Takahashi's team decided to do some training. In one set of training, a member can reduce his/her consumption coefficient by 1, as long as it does not go below 0. However, for financial reasons, the N members can do at most K sets of training in total.

What is the minimum possible score of the team, achieved by choosing the amounts of members' training and allocating the dishes optimally?

Constraints

All values in input are integers.

1 \leq N \leq 2 \times 10^5

0 \leq K \leq 10^{18}

1 \leq A_i \leq 10^6\ (1 \leq i \leq N)

1 \leq F_i \leq 10^6\ (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N
F_1 F_2 ... F_N

Output

Print the minimum possible score of the team.

Sample Input 1

3 5
4 2 1
2 3 1

Sample Output 1

2

They can achieve the score of 2, as follows:

Member 1 does 4 sets of training and eats Food 2 in (4-4) \times 3 = 0 seconds.

Member 2 does 1 set of training and eats Food 3 in (2-1) \times 1 = 1 second.

Member 3 does 0 sets of training and eats Food 1 in (1-0) \times 2 = 2 seconds.

They cannot achieve a score of less than 2, so the answer is 2.

Sample Input 2

3 8
4 2 1
2 3 1

Sample Output 2

0

They can choose not to do exactly K sets of training.

Sample Input 3

11 14
3 1 4 1 5 9 2 6 5 3 5
8 9 7 9 3 2 3 8 4 6 2

Sample Output 3

12



Sample input:
3 5
4 2 1
2 3 1


Sample output:
2

Submission status: Runtime Error

Solution code:
A.sort(reverse=True)
F.sort()
AF = [0]*N

for i in range(K):
    for j in range(N):
        AF[j] = A[j]*F[j]
    v = max(AF)
    maxIndex = AF.index(v)
    A[maxIndex] -= 1

for j in range(N):
      AF[j] = A[j]*F[j]

v = max(AF)
print(v)

Submission status: Runtime Error

Solution code:
def main():
    N,K=map(int,input().split())
    A=list(map(int,input().split()))
    F=list(map(int,input().split()))
    A.sort()
    F.sort(reverse=True)
    i = 0
    while K > 0:
        if A[0]*F[0] >= A[-1] * F[-1]:
            if K > A[0]:
                K -= A.pop(0)
            else:
                A[0] -= K
                K = 0
                break
        else:
            if K >= A[-1]:
                K -= A.pop(-1)
                F.pop(-1)
            else:
                A[-1] -= K
                K=0
                break
        
    S = 0
    for j in range(len(A)):
        S += A[j] * F[j]
    print(S)
    
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def main():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    f = list(map(int, input().split()))

    a.sort()
    f.sort(reverse=True)

    flag = 0

    ls = [ x*y for (x, y) in zip(a, f)]
    ls = [[ls[i], i] for i in range(n)]

    ls.sort(reverse=True)

    suma = sum(a)

    while k != 0:
        if k < suma:
            k -= 1
            a[ls[0][1]] -= 1
            ls[ls[0][1]] -= f[ls[0][1]]
            ls.sort(reverse=True)
        else:
            flag = 1
            break
    
    if flag = 1:
        ans = 0
    else:
        ans = ls[0][0]

    print(ans)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
alist = [s for s in map(int,input().split())]
flist = [s for s in map(int,input().split())]
alist.sort()
flist.sort(reverse=True)
t = [alist[i]*flist[i] for i in range(n)]
for i in range(k):
  ind = t.index(max(t))
  del t[ind]
  tmp = alist[ind]
  del alist[ind]
  alist.insert(ind, tmp-1)
  t.inseer(ind, alist[ind]*flist[ind])
print(max(t))

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
listA = list(map(int, input().split()))
listB = list(map(int, input().split()))

listA.sort()
listB.sort(reverse = True)
#print(listA)

count = 0
while K != 0:
    if listA[count] < K:
        K = K - listA[count]
        listA[count] = 0
    else:
        listA[count] = listA[count] - K
        K = 0
    count += 1
listA.sort()

answer = 0
for i in range(N):
    answer += listA[i] * listB[i]

#print(listA)
#print(listB)
print(answer)

Submission status: Runtime Error

Solution code:
import sys
import heapq
input = sys.stdin.readline

priority_que = []
N, K = map(int, input().split())
A = sorted(map(int, input().split()))
F = sorted(map(int, input().split()))[::-1]
if sum(A) <= K:
    print(0)
    exit()
hpop = heapq.heappushpop
hpush = heapq.heappush
score = [float('inf')] * K
for i, a in enumerate(A):
    f = F[i]
    key = f*a
    while key >= 0:
        # print(key)
        if len(priority_que) > K:
            if key <= priority_que[0]:
                break
            hpop(priority_que, key)
        else:
            hpush(priority_que, key)
        key -= f

# print(priority_que)
print(heapq.heappop(priority_que))

Submission status: Runtime Error

Solution code:
# At ABC 144 E (500)
n, k = map(int, input().split())
A = list(map(int, input().split()))
F = list(map(int, input().split()))

# N foods, difficuly F[i]
# max(A[i] * F[i])
# K trainings to reduce F[i] to at most 0

F.sort(reverse=True)
A.sort(reverse=False)

import heapq
Z = [] # heap
for i in range(n):
    mul = -1 * F[i] * A[i]
    t = (mul, F[i], A[i])
    if mul != 0:
        heapq.heappush(Z, t)

import math

while k > 0 and Z:
    _, f0, a0 = heapq.heappop(Z)
    if a0 > 0:
        a0 -= 1
        k -= 1
    if a0 > 0:
        heapq.heappush(Z, (-1 * f0 * a0, f0, a0))

ans = 0
for i in range(n):
    ans = max(ans, Z[i][1] * Z[i][2])
print(ans)

Submission status: Runtime Error

Solution code:
import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
mod = 10**9 + 7
inf = float('inf')
ans = []
N, K =LI()
A = LI()
F = LI()
A.sort(reverse=True)
F.sort()

disA = [0]*N
for i in range(N-1):
    disA[i] = A[i] - A[i+1]
disA[N-1] = A[-1]

sumA = sum(A)
#print(A)
k = int(-1)
cou = sumA
while k<N:
    if cou<=K:
        break
    k +=1
    cou = cou - disA[-k-1]*(N-k)

basic = A[-k-1]
#print(k)
for i in range(N-k-1):
    A[i] = basic
K = K - cou
#print(K)
for i in range(K):
    A[i]-=1
#print(A)
A.sort(reverse=True)

for i in range(N):
    ans.append(A[i]*F[i])
#print(A)
#print(F)
#print(ans)
if k ==-1:
    print("0")
else:
    print(max(ans))

Submission status: Runtime Error

Solution code:
import bisect
import math
(n,k),a,f = [list(map(int, s.split())) for s in open(0)]

if n == 1:
    ans = max((a[0] - k) * f[0], 0)
    print(ans)

else:
    a.sort()
    f.sort(reverse=True)
    s = []
    t = []
    for x,y in zip(a,f):
        s.append((x*y, y))
    s.sort()

    while len(s) > 0:
        t.append(s[-1])
        tmp = 0
        for l, y in t:
            tmp += max(1, math.ceil((l - s[-2][0]) / y))
        if k <= tmp:
            t = t[:-1]
            break
        s = s[:-1]
    
    for l, y in t:
        tmp = max(1, math.ceil((l - s[-1][0]) / y))
        k -= tmp
        l -= tmp * y
        bisect.insort(s, (l, y))
    
    while k > 0 and s[-1][0] > 0:
        l, y = s[-1]
        s = s[:-1]
        tmp = math.ceil((l - s[-1][0]) / y)
        if tmp == 0:
            tmp = 1
        if k > tmp:
            k -= tmp
        else:
            tmp = k
            k = 0
        l = l - tmp * y
        bisect.insort(s, (l, y))
    print(s[-1][0])

Submission status: Runtime Error

Solution code:
#E問題
import numpy as np 
N, K = map(int,input().split())
A = map(int,input().split())
F = map(int,input().split())

A = np.ndarray(A)
F = np.adarray(F)
A = A.sort()[::-1]
F = F.sort()

remain = K
i = 0
while remain > 0 and i < N:
    if remain >= A[i]:
        remain = remain-i
        A[i] = 0
    else:
        A[i] = A[i]-remain
        remain = 0
print(A*F)

Submission status: Runtime Error

Solution code:
N, K  = map(int, input().split())
As = sorted(list(map(int, input().split())))
Fs = sorted(list(map(int, input().split())),reverse=True)
Xs = sorted([(a*f,i) for i,(a,f) in enumerate(zip(As,Fs))],reverse=True)
# Xs =[a*f for a,f in zip(As,Fs)]
# print(Xs)
# print(As)
# print(Fs)
import heapq
q = []
INF = 10**6
heapq.heapify(q)
for i,(a,f) in enumerate(zip(As,Fs)):
    num = -(a*f*INF+i)
    heapq.heappush(q,num)
if K >= sum(As):
    print(0)
    exit()
for k in range(K):
    num = heapq.heappop(q)
    i = (-num)%INF
    n = (-num)//INF
    print(i,n,As[i],Fs[i])
    As[i] -= 1
    upd = -(As[i]*Fs[i]*INF+i)
    heapq.heappush(q,upd)
num = heapq.heappop(q)
ans = (-num)//INF
print(ans)


x_min = min(Xs)
ns = [max(0,A-x_min//F) for A,F in zip(As,Fs)]
print(ns)

Submission status: Runtime Error

Solution code:
N, M = list(map(int, input().split()))
K = list(map(int, input().split()))
C = list(map(int, input().split()))
K = sorted(K, reverse = True)
C = sorted(C, reverse = False)

prev = max(K)
m = 0
for i, k in enumerate(K):
  if prev == k:
    continue
  m += (prev - k) * i
  if m > M:
    m -= M
    break
  prev = k
  
print(prev * C[i - 1 - m])

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = input().split()
f = input().split()

a = [int(x) for x in a]
f = [int(x) for x in f]
t = [int(x * y) for x, y in a, f]

a.sort()
f.sort()
print(t)

a = a[::-1]
tmp = 0
time_max = 0

for i in range(k):
    time_max = 0
    for j in range(n - 1):
        time_j = a[j]*f[j]
        if time_max < time_j:
            time_max = time_j
        if time_max == 0:
            break
    if time_max == 0:
        break
    a[tmp] = a[tmp] - 1

time_max = 0
for j in range(n):
    time_j = a[j]*f[j]
    if time_max < time_j:
        time_max = time_j

print(time_max)

Submission status: Runtime Error

Solution code:
import heapq
import math
a,b=map(int,input().split())
c=list(map(int,input().split()))
d=list(map(int,input().split()))
if b>=sum(c):
  print(0)
else:
  c.sort()
  d.sort(reverse=True)
  e=[c[i]*d[i] for i in range(a)]
  f=[]
  for i in range(a):
    heapq.heappush(f,-e[i])
  k=0
  while k<b or f[0]==0:
    x=-heapq.heappop(f)
    y=e.index(x)
    z=min(b-k,(x+f[0])//d[y]+1)
    k+=z
    c[y]=c[y]-z
    e[y]=c[y]*d[y]
    heapq.heappush(f,-e[y])
    print(f)
  print(-f[0])

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
f=list(map(int,input().split()))
a.sort()
f.sort(reverse=True)
m=0
for i in range(n):
    m=max(m,a[i]*f[i])
x=m//2
l=0
r=m
def check(x):
    p=0
    for i in range(n):
        if x//f[i]<a[i]:
            p+=a[i]-x//f[i]
    if p>k:
        return False
    else:
        return True
while l<r:
    if check(x):
        l=x
        x=(r-l)//2
    else:
        r=x
        x=(r-l)//2
return(x)

Submission status: Runtime Error

Solution code:
import sys
import heapq
input = sys.stdin.readline

priority_que = []
N, K = map(int, input().split())
A = sorted(map(int, input().split()))
F = sorted(map(int, input().split()))[::-1]
#print(A)
#print(F)
score = [float('inf')] * K
for i, a in enumerate(A):
    f = F[i]
    for j in range(a+1):
        #print(f*j)
        if len(priority_que) > K:
            heapq.heappushpop(priority_que, f*j)
        else:
            heapq.heappush(priority_que, f*j)
#print(priority_que)
print(heapq.heappop(priority_que))

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
N, K = map(int, input().split(" "))
A = np.array(list(map(int, input().split(" "))))
F = np.array(list(map(int, input().split(" "))))

if K >= A.sum():
    print(0)
    sys.exit()

A = np.sort(A)
F = np.sort(F)[::-1]
print(A, F)
temp = (A * F).tolist()
for i in range(K):
    a = temp.argmax()
    temp[a] -= F[a]
    if sum(temp) == 0:
        break
print(np.array(temp).max())

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())                                                As = list(map(int, input().split()))
Fs = list(map(int, input().split()))                                                                                                                            As.sort()
As.reverse()                                                                    Fs.sort()
arr = []                                                                        M = 0
for a, f in zip(As, Fs):
    af = a*f                                                                        arr.append((af, a, f))                                                          M = af if af > M else M                                                     
f = -1                                                                          t = M                                                                           while f + 1 < t:
    m = f + (t-f) // 2
    k = K
    for AF, A, F in arr:                                                                d = A - m // F                                                                  if d > k:
            f = m
            break
        k -= d
    else:
        t = m

print(t)

Submission status: Runtime Error

Solution code:
import heapq
N, K = map(int, input().split())
A = sorted([int(i) for i in input().split()], reverse=True)
F = sorted([int(i) for i in input().split()])

if sum(A) <= K:
    print(0)
    exit()
else:
    hq = [-(A[i]*F[i]) for i in range(N)]
    heapq.heapify(hq)  # リストhqのheap化

    for i in range(K):
        c, a, f = heapq.heappop(hq)  # heap化されたリストhqから最小値を削除＆その最小値を出力

        a -= 1
        heapq.heappush(hq, (-(a*f), a, f))

    c, a, f = heapq.heappop(hq)  # heap化されたリストhqから最小値を削除＆その最小値を出力
    print(-c)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
F = list(map(int, input().split()))

A.sort()
F.sort(reverse=True)
AF = [[a, f] for a, f in zip(A, F)]

if sum(A)<K:
    print(0)
    quit()

while K>1:
    herasu = K//2
    AF.sort(key=lambda x: x[0]*x[1], reverse=True)
    for i in range(herasu):
        AF[i][0] -= 1
    K -= herasu

if K:
    AF.sort(key=lambda x: x[0]*x[1], reverse=True)
    for i in range(herasu):
        AF[i][0] -= 1

print(max(a*f for a, f in AF))

Submission status: Runtime Error

Solution code:
import sys
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs= sys.stdin.buffer.readlines
#rstrip().decode('utf-8')

#import math
#import numpy as np
#import operator
#from heapq import heapify,heappop,heappush
#from math import gcd
#from fractions import gcd
#from collections import deque
#from collections import defaultdict
#from collections import Counter
#from itertools import accumulate
#from itertools import groupby
#from itertools import permutations
#from itertools import combinations
#from scipy.sparse import csr_matrix
#from scipy.sparse.csgraph import floyd_warshall
#from scipy.sparse.csgraph import csgraph_from_dense
#from scipy.sparse.csgraph import dijkstra
#sys.setrecursionlimit(10**7)

#map(int,input().split())

def main():
	N,K=map(int,input().split())
	A=list(map(int,input().split()))
	F=sorted(list(map(int,input().split())))
	
	cost=sum(A)-K
	if cost<=0:
		print(0)
		exit(0)
	
	FF=[]
	for i in range(1,N+1):
		FF.append(F[0]*i)
	
	for i in range(1,N):
		for j in range(1,N+1):
			tmp=F[i]*j
			if tmp<FF[N-1]:
				FF.append(tmp)
			else:
				break
	FF.sort()
	print(FF[cost-1])
	

if __name__ == '__main__':
	main()

Submission status: Runtime Error

Solution code:
import copy
N, K = map(int,input().split())
A = list(map(int,input().split()))
F = list(map(int,input().split()))
X = []
A = sorted(A)
F = sorted(F)[::-1]
for i in range(N):
  X.append(A[i] * F[i])
XX = copy.deepcopy(X)

import heapq
from heapq import heapify

heapq._heapify_max(X)

def _heappush_max(heap, item):
    heap.append(item)
    heapq._siftdown_max(heap, 0, len(heap)-1)
def _heappop_max(heap):
    lastelt = heap.pop()
    if heap:
        returnitem = heap[0]
        heap[0] = lastelt
        heapq._siftup_max(heap, 0)
        return returnitem
    return lastelt

for i in range(K):
    x = _heappop_max(X)
    id = XX.index(x)
    if x < 1:
        _heappush_max(X,x)
        break
    else:
        A[id] -= 1
        x = A[id] * F[id]
        XX[id] = x
        _heappush_max(X,x)

print(max(X))

Submission status: Runtime Error

Solution code:
import math
import random
from operator import itemgetter
import re
import sys
from itertools import accumulate
from collections import defaultdict
from collections import deque
from bisect import bisect_left,bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
input = sys.stdin.readline
N,K = map(int,input().split())
A.sort()
F.sort(reverse=True)
print(A)
print(F)
maxi = 0
for i in range(N):
    maxi = max(maxi,A[i]*F[i])
start=0
end = maxi
while True:
    count = 0
    value = (start+end)//2
    for i in range(N):
        count += max(0,A[i]-value//F[i])
    if count == K:
        break
    elif count > K :
        if 2 > end-start:
            value +=1
            break
        start = value
    else:
        if 2 > end-start:
            break
        end = value
print(value)

Submission status: Runtime Error

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, atan2, degrees
from operator import mul
from functools import reduce
sys.setrecursionlimit(10**8)

INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n, k = LI()
A = sorted(LI())
F = sorted(LI(), reverse=True)


que = [(-A[i] * F[i], -F[i], A[i]) for i in range(n)]
heapify(que)
while k and que:
    x, f, a = heappop(que)
    if a:
        a -= 1
        x -= f
        heappush(que, (x, f, a))
        k -= 1



print(-min([que[i][0] for i in range(len(que))]))

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A_data = list(map(int, input().split()))
F_data = list(map(int, input().split()))

A_data.sort(reverse=True)
F_data.sort(reverse=True)

index=0
while(0 < K):
    if A_data[index] < K:
        K -= A_data[index]
        A_data[index] = 0
    else:
        A_data[index] -= K
        K = 0 
    index += 1
        
# for _ in range(K):
#     if A_data[index] <= 0:
#         index +=1
#     if len(A_data) <= index:
#         break
    
#     A_data[index] -= 1

combined = [x * y for (x, y) in zip(A_data, F_data)]
combined.sort(reverse=True)
print(combined[0])

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")
import math
import heapq


def solve(N: int, K: int, A: "List[int]", F: "List[int]"):
    h = []
    A.sort()
    F.sort(reverse=True)
    for a, f in zip(A, F):
        heapq.heappush(h, (-a*f, a, f))

    maxtime = heapq.nsmallest(1, h)
    maxtime = -maxtime[0][0]

    def isOK(y):
        hh = h.copy()
        counter = 0
        while len(hh) > 0:
            p, a, f = heapq.heappop(hh)
            if -p > y:
                counter += a-y//f
                if counter > K:
                    return False
            else:
                break
        return counter <= K

    def binary_search(x):
        ng = -1
        ok = len(x)
        while abs(ok - ng) > 1:
            mid = (ok + ng)//2
            # print("mid: {}, in ({}, {})".format(mid, ng, ok))
            if isOK(mid):
                ok = mid
            else:
                ng = mid
        return ng, ok

    ng, ok = binary_search(range(maxtime))
    print(ok)

    # while k > 0:
    #     p1, a1, f1 = heapq.heappop(h)
    #     p2, a2, f2 = heapq.heappop(h)
    #     p1, p2 = -p1, -p2
    #     sub = min(a1 - math.ceil((p2/f1)-1), k)
    #     a1 -= sub
    #     k -= sub
    #     heapq.heappush(h, (-a1*f1, a1, f1))
    #     heapq.heappush(h, (-a2*f2, a2, f2))
    # # print(h)
    # p, a, f = heapq.heappop(h)
    # print(-p)

    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
    K = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    F = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, K, A, F)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]
import heapq
n,k=map(int,input().split())
a=list(map(int,input().split()))
f=list(map(int,input().split()))
a.sort()
f.sort()
ans=[]
for i in range(n):
    ans.append([f[i]*a[n-i-1]*-1,a[n-i-1]*-1])
heapq.heapify(ans)
# print(ans)
for i in range(k):
    tmp=heapq.heappop(ans)
    # print(tmp)
    if tmp[1]==0:
        heapq.heappush(a,tmp)
        break
    tmp[0]=tmp[0]//tmp[1]
    tmp[1]+=1
    tmp[0]=tmp[0]*tmp[1]
    heapq.heappush(ans,tmp)
cnt=0
ans.sort()
print(ans[0][0]*-1)

Submission status: Runtime Error

Solution code:
import sys
from collections import Counter
input = sys.stdin.readline
sys.setrecursionlimit(100000)
def getN():
    return int(input())
def getList():
    return list(map(int, input().split()))

def check(mid, k, pairs):
    tmp = 0
    for pair in pairs:
        a,b = pair
        kari_a = mid // b
        tmp += max(a - kari_a, 0)

    if tmp <= k:
        return True
    else:
        return False


def solve():
    n, k = getList()
    cap = getList()
    foods = getList()
    cap.sort()
    foods.sort(reverse=True)
    h = []
    pairs = [(-a * b, a, b) for a, b in zip(cap, foods)]
    ansmn = 0
    ansmx = 10**7
    while(ansmx - ansmn > 1):
        mid = (ansmn + ansmx) // 2
        res = check(mid, k, pairs)
        if res:
            ansmn = mid
        else:
            ansmx = mid


    if check(ansmx, k, pairs):
        print(ansmx)
    else:
        print(ansmn)

def main():
    t = getN()
    for times in range(t):
        solve()


if __name__ == "__main__":
    main()