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: Time Limit Exceeded

Solution code:
import math

N, K = [int(x) for x in input().split()]
As = sorted([int(x) for x in input().split()])
Fs = sorted([int(x) for x in input().split()], reverse=True)

def in_n_sec(n):
  total_training = sum(max(0, a-int(n/f)) for a, f in zip(As, Fs))
  return total_training <= K
  
current_worst_confirmed = 10**12
current_best_possible = 0
while current_worst_confirmed > current_best_possible:
  to_try = (current_worst_confirmed + current_best_possible ) // 2
  if in_n_sec(to_try):
    current_worst_confirmed = to_try
  else:
    current_best_possible = to_try + 1
print(current_worst_confirmed)

Submission status: Time Limit Exceeded

Solution code:
import heapq

N, K = map(int, input().split())
A = list(map(int, input().split()))
F = list(map(int, input().split()))
A = [A[i] * (-1) for i in range(N)]
heapq.heapify(A)
heapq.heapify(F)
AF = []
for _ in range(N):
	t_a = heapq.heappop(A)
	t_f = heapq.heappop(F)
	AF.append([t_a*t_f, t_f])

heapq.heapify(AF)
for _ in range(K):
	t,f = heapq.heappop(AF)
	heapq.heappush(AF,[min(0,t+f), f])

ans, f = heapq.heappop(AF)
print(ans*(-1))

Submission status: Time Limit Exceeded

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

A.sort()
F.sort(reverse=True)
B = [[A[i], F[i]] for i in range(N)]


for i in range(K):
    B.sort(reverse=True, key=lambda x: x[0]*x[1])
    if B[0][0] > 0:
        B[0][0] -= 1
    else:
        break
B.sort(reverse=True, key=lambda x: x[0]*x[1])
print(B[0][1]*B[0][0])

Submission status: Time Limit Exceeded

Solution code:
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())))

for _ in range(K):
    A.sort()
    F.sort()
    F = F[::-1]
    i = np.argmax(A * F)
    A[i] -= 1
print(np.amax(A * F))

Submission status: Time Limit Exceeded

Solution code:
import heapq

N, K = map(int, input().split())
A = sorted(list(map(int, input().split())))
F = sorted(list(map(int, input().split())), reverse = True)

flg = 0
heap = []

for i in range(N):
	heapq.heappush(heap, [- A[i] * F[i], A[i], F[i]])
	
for i in range(K):
	score, tmp_A, tmp_F = heapq.heappop(heap)
	if tmp_A > 0:
		tmp_A -= 1
		heapq.heappush(heap, [- tmp_A * tmp_F, tmp_A, tmp_F])
	else:
		flg = 1
		break
		
if flg:
	print(0)
else:
	ret = heapq.heappop(heap)
	print(-1 * ret[0])

Submission status: Time Limit Exceeded

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


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 = copy.copy(h)
        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: Time Limit Exceeded

Solution code:
import heapq

N, K = map(int, input().split())
A = sorted(list(map(int, input().split())))
F = sorted(list(map(int, input().split())) ,reverse=True)

AF = []
for a, f in zip(A, F):
    AF.append((-a*f, -a))

heapq.heapify(AF)
for i in range(K):
    mul, val = heapq.heappop(AF)
    val = -val
    if val:
        temp = mul // val
        val -= 1
        heapq.heappush(AF, (temp * val, -val))


print(-AF[0][0])

Submission status: Time Limit Exceeded

Solution code:
def solve():
  N, K = map(int, input().split())
  A = [int(i) for i in input().split()]
  F = [int(i) for i in input().split()]

  rest = sum(A) - K
  cost = 0

  while True:
    if rest <= 0: return cost
    cost += 1
    rest -= len([0 for f in F if cost % f == 0])

print(solve())

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
A=list(map(int,input().split()))
A.sort()
F=list(map(int,input().split()))
F.sort(reverse=True)
def is_ok(x):
  c=0
  for i in range(n):
    c+=max(A[i]-x//F[i],0)
  if c<=k:
    return True
  else:
    return False
l=0
r=A[-1]*F[0]
while l!=r:
  m=(l+r)//2
  if is_ok(m):
    r=m
  else:
    l=m+1
print(l)

Submission status: Time Limit Exceeded

Solution code:
def judge(n, k, a_list_s, f_list_s, v):
    res = 0
    # print(v)
    for i in range(n):
        a_necessary = v // f_list_s[i]
        # print(a_necessary, a_list_s[i])
        if a_list_s[i] > a_necessary:
            res += a_list_s[i] - a_necessary
    if res > k:
        return False
    else:
        return True


def solve_e(n, k, a_list, f_list):

    if sum(a_list) <= k:
        return 0
    
    a_list_s = sorted(a_list)
    f_list_s = sorted(f_list, reverse=True)

    left = 0
    right = 10 ** 12

    while right - left > 1:
        middle = (left + right) // 2
        if judge(n, k, a_list_s, f_list_s, middle):
            right = middle
        else:
            left = middle
    return right


def main():
    # input
    n, k = map(int, input().split())
    a_list = list(map(int, input().split()))
    f_list = list(map(int, input().split()))
    res = solve_e(n, k, a_list, f_list)
    print(res)


def test():
    assert solve_e(3, 5, [4, 2, 1], [2, 3, 1]) == 2
    assert solve_e(3, 8, [4, 2, 1], [2, 3, 1]) == 0
    assert solve_e(
        11, 14, [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5],
        [8, 9, 7, 9, 3, 2, 3, 8, 4, 6, 2]) == 12


if __name__ == "__main__":
    test()
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1

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


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, K, A, F):
    A.sort(reverse=True)
    F.sort()

    cost = [[-a * f, a, f] for a, f in zip(A, F)]

    heapq.heapify(cost)
    while cost and K > 0:
        if len(cost) >= 2:
            l1 = heapq.heappop(cost)
            l2 = heapq.heappop(cost)
            diff = -(l1[0] - l2[0])
            r = diff // l1[2]
            if r == 0:
                r = 1
            if K >= r:
                K -= r
            else:
                r = K
                K = 0
            na = l1[1] - r
            l1[0] = -(na * l1[2])
            l1[1] = na
            if l1[1] != 0:
                heapq.heappush(cost, l1)
            heapq.heappush(cost, l2)
        else:
            _, a, f = heapq.heappop(cost)
            return max(0, a-K) * f

    ans = 0
    for c, _, __ in cost:
        ans = max(ans, -c)
    return ans


def main():
    N, K = read_int_n()
    A = read_int_n()
    F = read_int_n()
    print(slv(N, K, A, F))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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 
        
# 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: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
a=[int(x) for x in input().split()]
f=[int(x) for x in input().split()]
a.sort()
f.sort()
for l in range(k):
    d=0
    if a[n-1]==0:
        break
    for c in range(1,n):
        if a[c]*f[n-1-c]>a[d]*f[n-1-d]:
            d=c
    a[d]=a[d]-1
s=a[0]*f[n-1]
for c in range(1,n):
    if a[c]*f[n-1-c]>s:
        s=a[c]*f[n-1-c]
print(s)

Submission status: Time Limit Exceeded

Solution code:
import math

N, K = [int(x) for x in input().split()]
As = sorted([int(x) for x in input().split()])
Fs = sorted([int(x) for x in input().split()], reverse=True)

def in_n_sec(n):
  #print(n)
  #print(Fs)
  max_allowed = [int(n/F) for F in Fs]
  #print(max_allowed)
  #print(As)
  #print([max(0, a-ma) for a, ma in zip(As, max_allowed)])
  total_training = sum(max(0, a-ma) for a, ma in zip(As, max_allowed))
  #print(total_training)
  return total_training <= K
  
current_worst_confirmed = 10**12
current_best_possible = 0
while current_worst_confirmed > current_best_possible:
  #print(current_worst_confirmed, current_best_possible)
  to_try = (current_worst_confirmed + current_best_possible ) // 2
  if in_n_sec(to_try):
    current_worst_confirmed = to_try
  else:
    current_best_possible = to_try + 1
print(current_worst_confirmed)

Submission status: Time Limit Exceeded

Solution code:
ii = lambda: int(input())
mis = lambda: map(int,input().split())
lmis = lambda: list(mis())

nk = lmis()
N,K = nk[0],nk[1]
A = lmis()
F = lmis()

F = sorted(F)
A = sorted(A,reverse=True)
for i in range(K):
    if(A[0]>0):
        m = 0
        ind = 0
        for j in range(N):
            if m < A[j]*F[j]:
                m = A[j]*F[j]
                ind = j
        A[ind] -= 1
        A = sorted(A,reverse=True)
m = 0
for i in range(N):
    if m < A[i]*F[i]:
        m = A[i]*F[i]
print(m)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
f = list(map(int, input().split()))
a.sort(reverse=True)
f.sort()
m = [i * j for i, j in zip(a, f)]
for i in range(k):
    t = max(m)
    if t <= 0:
        print(0)
        break
    l = m.index(t)
    a[l] -= 1
    m[l] = a[l] * f[l]
else:
    print(max(m))

Submission status: Time Limit Exceeded

Solution code:
import heapq as hq
N, K = map(int, input().split())
A = list(map(int,input().split()))
A.sort()
F = list(map(int,input().split()))
F.sort()
q = [(-A[i]*F[N-1-i], F[N-1-i]) for i in range(N)]
hq.heapify(q)
cnt = 0
while cnt < K:
	cnt += 1
	c = hq.heappop(q)
	if c[0] < 0:
		hq.heappush(q, (c[0]+c[1], c[1]))
	else:
		hq.heappush(q, c)
		break
print(-hq.heappop(q)[0])

Submission status: Time Limit Exceeded

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

a = sorted(a, reverse=True)
f = sorted(f)
p = [i*j for i, j in zip(a, f)]

while True:
    for i in range(n):
        if k <= 0:
            break
        while True:
            if a[i] == 0 or p[i] < max(p) or k <= 0:
                break
            a[i] -= 1
            k -= 1
            p[i] = a[i] * f[i]
    if k <= 0 or sum(p) <= 0:
        break

print(max(p))

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import *

def main():
	input = sys.stdin.readline

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

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

	cost = []
	for ai, fi in zip(A,F):
		heappush(cost,(ai*fi*-1,ai,fi))

	while K>0:
		cmax, ai, fi = heappop(cost)
		if cmax==0: break
		csec = min(cost[0][0],cost[1][0])
		count = (csec-cmax)//ai + 1
		if count>K: count = K
		# print(count)
		aj = ai-count
		fj = fi
		cj = aj*fj*-1
		heappush(cost,(cj,aj,fj))
		K -= count

	ans = cost[0][0]*-1
	print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int, input().strip().split(' '))
A = sorted(list(map(int, input().strip().split(' '))), reverse=True)
F = sorted(list(map(int, input().strip().split(' '))))

def argmax(x):
  return max(enumerate(x), key=lambda x:x[1])[0]

while K > 0:
  now_costs = [a*f for a, f in zip(A, F)]
  if max(now_costs) < 1: break
  A[(argmax(now_costs))] -= 1
  K -= 1
print(max([a*f for a, f in zip(A, F)]))

Submission status: Time Limit Exceeded

Solution code:
import heapq 
N, K = [int(x) for x in input().split()]
A = sorted([int(x) for x in input().split()])
F = sorted([int(x) for x in input().split()], reverse=True)
h = []
if (sum(A) <= K):
    print(0)
else:
    for a, f in zip(A, F):
        heapq.heappush(h, (-a*f, [a, f]))
    for i in range(K):
        before = heapq.heappop(h)
        a, f = before[1]
        heapq.heappush(h, (-(a-1)*f, [a-1, f]))
    print(-1 * heapq.heappop(h)[0])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np


def solve(n, k, aaa, fff):
    aaa = np.sort(aaa)
    fff = np.sort(fff)[::-1]

    l = 0
    r = 10 ** 12 + 1
    while l < r - 1:
        m = (l + r) // 2
        req = np.clip(aaa - m // fff, 0, None).sum()
        # print(aaa, m // fff, m, req)
        if req > k:
            l = m + 1
        else:
            r = m + 1
    return l


n, k = list(map(int, input().split()))
aaa = np.array(list(map(int, input().split())), dtype=np.int64)
fff = np.array(list(map(int, input().split())), dtype=np.int64)

print(solve(n, k, aaa, fff))

Submission status: Time Limit Exceeded

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
a.sort()
b.sort(reverse=True)
#print(a)
#print(b)
c = []
for i in range(n):
  c.append([-a[i]*b[i],b[i]])
#print(c)
import heapq
heapq.heapify(c)
for _ in range(k):
  now = heapq.heappop(c)
  if now[0] == 0:
    heapq.heappush(c,now)
    break
  heapq.heappush(c, [now[0]+now[1],now[1]] )
#print(c)
ans = 0
for i in range(n):
  if ans > c[i][0]:
    ans = c[i][0]
print(-1*ans)

Submission status: Time Limit Exceeded

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)

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)

for k in range(K):
    num = heapq.heappop(q)
    # print(num)
    i = (-num)%INF
    As[i] -= 1
    upd = -(As[i]*Fs[i]*INF+i)
    heapq.heappush(q,upd)
num = heapq.heappop(q)
ans = (-num)//INF
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq

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

F = sorted(F, reverse = True)
A = sorted(A)
flg = 0
heap = []

for i in range(N):
	heapq.heappush(heap, [- A[i] * F[i], A[i], F[i]])
	
for i in range(K):
	score, tmp_A, tmp_F = heapq.heappop(heap)
	if tmp_A > 0:
		tmp_A -= 1
		heapq.heappush(heap, [- tmp_A * tmp_F, tmp_A, tmp_F])
	else:
		flg = 1
		break
		
if flg:
	print(0)
else:
	ret = heapq.heappop(heap)
	print(-1 * ret[0])

Submission status: Time Limit Exceeded

Solution code:
import heapq

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

A = sorted(A)
F = sorted(F, reverse = True)

AF = [[A[i]*F[i]*(-1), F[i]] for i in range(N)]
heapq.heapify(AF)
for _ in range(K):
	t,f = heapq.heappop(AF)
	heapq.heappush(AF,[min(0,t+f), f])

ans, f = heapq.heappop(AF)
print(ans*(-1))

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
f = list(map(int, input().split()))
a.sort(reverse=True)
f.sort()
m = [i * j for i, j in zip(a, f)]
for i in range(k):
    l = m.index(max(m))
    a[l] -= 1
    m[l] = a[l] * f[l]
    if max(m) <= 0:
        print(0)
        break
else:
    print(max(m))

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush
from operator import itemgetter
from collections import deque, defaultdict, Counter
from bisect import bisect_left, bisect_right
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
MOD = 10**9 + 7
INF = float('inf')

def sol():
    _, K = map(int, input().split())
    A = list(map(int, input().split()))
    F = list(map(int, input().split()))

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

    def isOk(t):
        cnt = 0
        for a, f in zip(A, F):
            ness = t // f
            if a <= ness:
                continue
            cnt += a - ness

        if cnt > K:
            return False
        else:
            return True

    ng = -1
    ok = max(A) * max(F) + 10

    while ok - ng > 1:
        mid = (ok + ng) // 2
        if isOk(mid):
            ok = mid
        else:
            ng = mid
    print(ok)


sol()

Submission status: Time Limit Exceeded

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

A.sort()
F.sort(reverse=True)
q = []
for i in range(N):
    heapq.heappush(q, (-(A[i]*F[i]), A[i], F[i]))

for k in range(K):
    p, a, f = heapq.heappop(q)
    if p < 0:
        heapq.heappush(q, ((-(a-1)*f), a-1, f))
    else:
        break

p, a, f = heapq.heappop(q)
print(-p)

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int,input().split())
a_list=[int(x) for x in input().split()]
f_list=[int(x) for x in input().split()]
import heapq
sa=sorted(a_list)
sf=sorted(f_list)[::-1]
pl_orig=[-x*y for (x,y) in zip(sa,sf)]
pl=[-x*y for (x,y) in zip(sa,sf)]
for k in range(K):
    heapq.heapify(pl)
    max_pl=heapq.heappop(pl)
    max_id=pl_orig.index(max_pl)
    sa[max_id]-=1
    max_pl=heapq.heappush(pl,-1*sa[max_id]*sf[max_id])
    pl_orig[max_id]=-1*sa[max_id]*sf[max_id]
print(-1*heapq.heappop(pl))

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int, input().strip().split(' '))
A = sorted(list(map(int, input().strip().split(' '))), reverse=True)
F = sorted(list(map(int, input().strip().split(' '))))

def argmax(vec):
  max_i = set()
  max_v = 0
  for i, v in enumerate(vec):
    if v > max_v:
      max_v = v
      max_i = {i}
    elif v == max_v:
      max_i.add(i)
  return max_i

while K > 0:
  now_costs = [a*f for a, f in zip(A, F)]
  if max(now_costs) < 1: break
  bottleneck = argmax(now_costs)
  if len(bottleneck) > K: break
  for b in bottleneck:
    A[b] -= 1
  K -= len(bottleneck)
print(max([a*f for a, f in zip(A, F)]))

Submission status: Time Limit Exceeded

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


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

    F.sort(reverse=True)
    A.sort()
    l = -1
    r = 0
    for i in range(N):
        if A[i]*F[i] > r:
            r = A[i]*F[i]
    r += 1
    while r-l > 1:
        m = (r+l)//2
        q = []
        for f in F:
            hp.heappush(q, m//f)
        cost = 0
        for a in A:
            f = hp.heappop(q)
            cost += max(0, a-f)
        if cost <= K:
            r = m
        else:
            l = m

    print(r)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
#設定
import sys
input = sys.stdin.buffer.readline

from heapq import heappop, heappush

INF = float("inf")

def getlist():
	return list(map(int, input().split()))

#処理内容
def main():
	N, K = getlist()
	A = getlist()
	F = getlist()
	A = sorted(A)
	F = sorted(F)
	Q = []
	for i in range(N):
		heappush(Q, [ (-A[i]) * F[N - 1 - i], -A[i], -F[N - 1 - i]])
	#print(Q)
	#処理
	for i in range(K):
		if Q[0][0] == 0:
			break
		else:
			s, a, f = heappop(Q)
			a += 1
			s = -(a * f)
			heappush(Q, [s, a, f])
	#print(Q)
	ans = 0
	for i in range(N):
		ans = max(ans, -Q[i][0])
	print(ans)

if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

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)

import heapq
q = []
heapq.heapify(q)
for i,(a,f) in enumerate(zip(As,Fs)):
    heapq.heappush(q,(-a*f,i))
    
for k in range(K):
    a,i = heapq.heappop(q)
    # print(-a,i)
    As[i] -= 1
    upd = (As[i])*Fs[i]
    heapq.heappush(q,(-upd,i))
ans,i = heapq.heappop(q)
print(-ans)



# print("A",As)
# print("F",Fs)

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import *

input = sys.stdin.readline

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

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

cost = []
for i in range(N):
	ai, fi = A[i], F[i]
	heappush(cost,(ai*fi*-1,ai,fi))

while K>0:
	cmax, ai, fi = heappop(cost)
	if cmax==0: break
	csec = min(cost[0][0],cost[1][0])
	count = (csec-cmax)//ai + 1
	if count>K: count = K
	# print(count)
	aj = ai-count
	fj = fi
	cj = aj*fj*-1
	heappush(cost,(cj,aj,fj))
	K -= count

ans = cost[0][0]*-1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
get = lambda: int(raw_input().strip())
gets = lambda: map(int, raw_input().strip().split())

# fi = open('sample3.in', 'r')
# raw_input = fi.readline

N, K = gets()
A = sorted(gets())
F = sorted(gets())[::-1]

if sum(A) <= K:
    print 0
    exit()


left = 0
avg = K / N
right = max(A[i] * (F[i] - avg) for i in xrange(N))

while left < right:
    mid = (left + right) / 2
    need = 0
    for i in xrange(N):
        need += max(A[i] - mid / F[i], 0)
    if need > K:
        left = mid + 1
    else:
        right = mid
print left

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int,input().split())
a_list=[int(x) for x in input().split()]
f_list=[int(x) for x in input().split()]
import heapq
sa=sorted(a_list)
sf=sorted(f_list)[::-1]
for k in range(K):
    pl_orig=[-x*y for (x,y) in zip(sa,sf)]
    pl=[-x*y for (x,y) in zip(sa,sf)]
    heapq.heapify(pl)
    max_pl=heapq.heappop(pl)
    max_id=pl_orig.index(max_pl)
    sa[max_id]-=1
pl_orig=[x*y for (x,y) in zip(sa,sf)]
print(max(pl_orig))

Submission status: Time Limit Exceeded

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))
    k = K
    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: Time Limit Exceeded

Solution code:
N, K = map(int,input().split())
A = list(map(int,input().split()))
F = list(map(int,input().split()))
A = sorted(A)
F = sorted(F, reverse=True)
mul = [A[i]*F[i] for i in range(N)]
for k in range(K):
    idx = mul.index(max(mul))
    if mul[idx] == 0:
        break
    mul[idx] -= F[idx]
print(max(mul))

Submission status: Time Limit Exceeded

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)
# print("X",Xs)

import heapq
q = []
heapq.heapify(q)
for i,(a,f) in enumerate(zip(As,Fs)):
    heapq.heappush(q,(-a*f,i))

for k in range(K):
    a,i = heapq.heappop(q)
    # print(-a,i)
    As[i] -= 1
    upd = (As[i])*Fs[i]
    heapq.heappush(q,(-upd,i))
ans,i = heapq.heappop(q)
print(-ans)



# print("A",As)
# print("F",Fs)

Submission status: Time Limit Exceeded

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

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

def isok(b):
    k = 0
    for a,f in zip(A,F):
        if a > b//f:
            k += a-(b//f)
            if k > K:
                return False
    return True

ok = 10**12+1
ng = 0

while ok-ng > 1:
    m = (ok+ng)//2
    if isok(m):
        ok = m
    else:
        ng = m
print(ok)

Submission status: Time Limit Exceeded

Solution code:
import heapq
n,k=map(int,input().split())
a=list(map(int,input().split()))
f=list(map(int,input().split()))
a.sort()
f.sort()
f.reverse()
l=[]
for i in range(n):
  l.append([-a[i]*f[i],-f[i],a[i]])
heapq.heapify(l)
for i in range(k):
  x=heapq.heappop(l)
  heapq.heappush(l,[-(max(x[2]-1,0))*(-x[1]),x[1],max(x[2]-1,0)])
l=list(l)
L=[]
for i in range(n):
  L.append(l[i][0])
print(-min(L))

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[]]*num
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################

import heapq
class Reverse:
    def __init__(self, val):
        self.val = val
        
    def __lt__(self, other):
        return self.val > other.val
        
    def __repr__(self):
        return repr(self.val)
    
class Heapq:
    def __init__(self, arr, desc = False):
        if desc:
            for i in range(len(arr)):
                arr[i] = Reverse(arr[i])
        self.desc = desc
        self.hq = arr
        heapq.heapify(self.hq)
 
    def pop(self):
        if self.desc: return heapq.heappop(self.hq).val
        else: return heapq.heappop(self.hq)
 
    def push(self, a):
        if self.desc: heapq.heappush(self.hq, Reverse(a))
        else: heapq.heappush(self.hq, a)
 
    def top(self):
        if self.desc: return self.hq[0].val
        else: return self.hq[0]

N,K = II()
A = III()
F = III()

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

z = Heapq([],True)
for i in range(N):
    z.push((A[i]*F[i],A[i],F[i]))

num = 0
for i in range(K):
    if num<N:
        z1 = z.pop()
        if z1[1] > 1:
            z.push(((z1[1]-1)*z1[2],z1[1]-1,z1[2]))
        else:
            num += 1
    else:
        print(0)
        exit()

print(z.top()[0])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import math
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
INF = 10**15

n, k = [int(item) for item in input().split()]
a = [int(item) for item in input().split()]
f = [int(item) for item in input().split()]
a.sort()
f.sort(reverse=True)

l = -1; r = 10**12 + 1 
while r - l > 1:
    mid = (l + r) // 2
    syugyo = 0
    for aa, ff in zip(a, f):
        target = mid // ff
        syugyo += max(aa - target, 0)
    if syugyo <= k:
        r = mid
    else:
        l = mid
print(r)

Submission status: Time Limit Exceeded

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

a.sort()
f.sort()
f = f[::-1]

import heapq
af = []
heapq.heapify(af)
for i in range(len(a)):
    heapq.heappush(af, [a[i] * f[i] * -1, f[i]])

for i in range(k):
    tmp = heapq.heappop(af)
    tmp[0] = (tmp[0] // tmp[1] + 1) * tmp[1]
    heapq.heappush(af, tmp)

print(max(heapq.heappop(af)[0] * -1, 0))