Petya is preparing for his birthday. He decided that there would be $n$ different dishes on the dinner table, numbered from $1$ to $n$. Since Petya doesn't like to cook, he wants to order these dishes in restaurants.

Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his orders from $n$ different places. To speed up this process, he wants to order courier delivery at some restaurants. Thus, for each dish, there are two options for Petya how he can get it:  the dish will be delivered by a courier from the restaurant $i$, in this case the courier will arrive in $a_i$ minutes,  Petya goes to the restaurant $i$ on his own and picks up the dish, he will spend $b_i$ minutes on this. 

Each restaurant has its own couriers and they start delivering the order at the moment Petya leaves the house. In other words, all couriers work in parallel. Petya must visit all restaurants in which he has not chosen delivery, he does this consistently.

For example, if Petya wants to order $n = 4$ dishes and $a = [3, 7, 4, 5]$, and $b = [2, 1, 2, 4]$, then he can order delivery from the first and the fourth restaurant, and go to the second and third on your own. Then the courier of the first restaurant will bring the order in $3$ minutes, the courier of the fourth restaurant will bring the order in $5$ minutes, and Petya will pick up the remaining dishes in $1 + 2 = 3$ minutes. Thus, in $5$ minutes all the dishes will be at Petya's house.

Find the minimum time after which all the dishes can be at Petya's home.


-----Input-----

The first line contains one positive integer $t$ ($1 \le t \le 2 \cdot 10^5$) — the number of test cases. Then $t$ test cases follow.

Each test case begins with a line containing one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of dishes that Petya wants to order.

The second line of each test case contains $n$ integers $a_1 \ldots a_n$ ($1 \le a_i \le 10^9$) — the time of courier delivery of the dish with the number $i$.

The third line of each test case contains $n$ integers $b_1 \ldots b_n$ ($1 \le b_i \le 10^9$) — the time during which Petya will pick up the dish with the number $i$.

The sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.


-----Output-----

For each test case output one integer — the minimum time after which all dishes can be at Petya's home.


-----Example-----
Input
4
4
3 7 4 5
2 1 2 4
4
1 2 3 4
3 3 3 3
2
1 2
10 10
2
10 10
1 2

Output
5
3
2
3

Source: codeforces | Difficulty: MEDIUM
Tags: Sorting

Greedy algorithms


Solutions:
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop
import math
from collections import *
from functools import reduce, cmp_to_key, lru_cache
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
M = mod = 10 ** 9 + 7

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip().split()]

def st():
	return str(input().rstrip())[2:-1]

def val():
	return int(input().rstrip())

def li2():
	return [str(i)[2:-1] for i in input().rstrip().split()]

def li3():
	return [int(i) for i in st()]
l1 = n = l2 = 0

def check(threshold):
	global l1, l2, n
	pos = 0
	for i in range(n):
		if l1[i] > threshold:
			pos += l2[i]
	return True if pos <= threshold else False
for _ in range(val()):
	n = val()
	l1 = li()
	l2 = li()
	low = 0
	ans = high = 10 ** 20
	while low <= high:
		mid = low + high >> 1
		if check(mid):
			ans = mid
			high = mid - 1
		else:
			low = mid + 1
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	n = int(input())
	a = map(int, input().split())
	b = map(int, input().split())
	zipp_list = zip(a, b)
	sorted_pair = sorted(zipp_list)
	tuples = zip(*sorted_pair)
	(restoran, petya) = [list(tuple) for tuple in tuples]
	restoran = [-1] + restoran
	petya = [-1] + petya
	lo = 0
	hi = n
	naj = float('inf')
	while lo <= hi:
		mid = (lo + hi) // 2
		dostavljac = max(restoran[:mid + 1])
		auto = sum(petya[mid + 1:])
		rj = max(dostavljac, auto)
		if rj < naj:
			naj = rj
		if dostavljac > auto:
			hi = mid - 1
		elif auto > dostavljac:
			lo = mid + 1
		else:
			lo = hi = mid
			break
	print(naj)


R = lambda : map(int, input().split())
(t,) = R()
for _ in [0] * t:
	R()
	a = []
	b = [0]
	s = 0
	for (x, y) in sorted(zip(R(), R()))[::-1]:
		a += (x,)
		s += y
		b += (s,)
	print(min(map(max, a + b, b)))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	s = 0
	ss = 0
	l = []
	for i in range(n):
		l.append([a[i], b[i]])
	l.sort()
	kkk = sum([l[j][1] for j in range(n)])
	kk = kkk
	for i in range(n):
		kkk -= l[i][1]
		bb = max(l[i][0], kkk)
		if kk > bb:
			kk = bb
	print(kk)


from sys import stdin
input = stdin.readline

def dish(deli, pick):
	if len(deli) == 1:
		return min(deli[0], pick[0])
	blanck = list(zip(deli, pick))
	temp = 0
	deliv = 0
	blanck = sorted(blanck, key=lambda s: s[0], reverse=True)
	for i in blanck:
		if i[0] <= temp + i[1]:
			deliv = max(i[0], deliv)
		else:
			temp += i[1]
	return max(temp, deliv)
t = int(input())
for i in range(t):
	a = input()
	lst1 = list(map(int, input().strip().split()))
	lst2 = list(map(int, input().strip().split()))
	print(dish(lst1, lst2))


def check(a, b, n, m):
	s = 0
	for i in range(n):
		if a[i] > m:
			s += b[i]
	return s <= m
T = int(input())
for _ in range(T):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	r = 10 ** 9
	l = 0
	while l <= r:
		m = (l + r) // 2
		if check(a, b, n, m):
			r = m - 1
		else:
			l = m + 1
	print(l)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	now = []
	for i in range(n):
		now.append((a[i], b[i]))
	now.sort(reverse=True)
	summary = 0
	max_value = 0
	for i in range(n):
		if summary + now[i][1] < now[i][0]:
			summary += now[i][1]
		else:
			max_value = max(max_value, now[i][0])
	print(max(summary, max_value))


import sys
m = int(sys.stdin.readline())
for _ in range(m):
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	b = list(map(int, sys.stdin.readline().split()))
	c = []
	for i in range(n):
		c.append((a[i], b[i]))
	c.sort(reverse=True)
	t = 0
	for x in c:
		if t + x[1] >= x[0]:
			t = max(t, x[0])
			break
		else:
			t += x[1]
	sys.stdout.write('{}\n'.format(t))


for _ in range(int(input())):
	n = int(input())
	rest = list(map(int, input().split()))
	self = list(map(int, input().split()))
	arr = []
	for i in range(n):
		arr.append([rest[i], self[i]])
	arr.sort()
	temp = 0
	time = max(rest)
	for i in reversed(range(n)):
		temp += arr[i][1]
		if temp < arr[i][0]:
			time = temp
		else:
			temp -= arr[i][1]
			time = max(temp, arr[i][0])
			break
	print(time)


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	arr = list(zip(map(int, input().split()), map(int, input().split())))
	arr.sort(key=lambda x: x[0], reverse=True)
	pre = [0]
	for i in arr:
		pre.append(pre[-1] + i[1])
	pre = pre[::-1]
	arr.reverse()
	i = 0
	out = pre[0]
	while i < n:
		out = min(out, max(pre[i + 1], arr[i][0]))
		i += 1
	print(out)


for _ in range(int(input())):
	a = int(input())
	b = list(map(int, input().split()))
	c = list(map(int, input().split()))
	k = sorted(zip(b, c))
	ans = sum(c)
	out = ans
	for i in k:
		ans -= i[1]
		out = min(out, max(i[0], ans))
	print(out)


from sys import stdin
input = stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ptime = 0
	c = [[a[i], b[i]] for i in range(n)]
	c.sort(reverse=True)
	i = 0
	ans = sum(b)
	while i < n:
		if ptime > c[i][0]:
			ans = ptime
			break
		if ptime + c[i][1] >= c[i][0]:
			ans = c[i][0]
			break
		ptime += c[i][1]
		i += 1
	print(ans)


from heapq import heappush, heappop
for _ in range(int(input())):
	l = []
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	heap = []
	for i in range(n):
		heappush(heap, [-a[i], b[i]])
	walk_cost = 0
	delivary_cost = 0
	while heap:
		if walk_cost + heap[0][1] >= -heap[0][0]:
			delivary_cost = max(-heap[0][0], walk_cost)
			break
		else:
			walk_cost += heap[0][1]
			heappop(heap)
	print(max(delivary_cost, walk_cost))


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	A = input().split()
	B = input().split()
	C = [(int(A[i]), int(B[i])) for i in range(n)]
	ans = 0
	for (a, b) in sorted(C, reverse=True):
		if ans > a:
			break
		if ans + b >= a:
			ans = a
			break
		ans += b
	print(ans)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter
from itertools import combinations
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192
from sys import stderr

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def pow(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def gcd(a, b):
	if a == b:
		return a
	while b > 0:
		(a, b) = (b, a % b)
	return a

def prefix_sum(ar):
	return list(accumulate(ar))

def suffix_sum(ar):
	return list(accumulate(ar[::-1]))[::-1]

def N():
	return int(inp())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]

def YES():
	print('YES')

def NO():
	print('NO')

def Yes():
	print('Yes')

def No():
	print('No')
from collections import defaultdict

def numberOfSetBits(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	return ((i + (i >> 4) & 252645135) * 16843009 & 4294967295) >> 24

class MergeFind:

	def __init__(self, n):
		self.parent = list(range(n))
		self.size = [1] * n
		self.num_sets = n

	def find(self, a):
		to_update = []
		while a != self.parent[a]:
			to_update.append(a)
			a = self.parent[a]
		for b in to_update:
			self.parent[b] = a
		return self.parent[a]

	def merge(self, a, b):
		a = self.find(a)
		b = self.find(b)
		if a == b:
			return
		self.num_sets -= 1
		self.parent[a] = b
		self.size[b] += self.size[a]

	def set_size(self, a):
		return self.size[self.find(a)]

	def __len__(self):
		return self.num_sets

def primesbelow(N):
	correction = N % 6 > 1
	N = {0: N, 1: N - 1, 2: N + 4, 3: N + 3, 4: N + 2, 5: N + 1}[N % 6]
	sieve = [True] * (N // 3)
	sieve[0] = False
	for i in range(int(N ** 0.5) // 3 + 1):
		if sieve[i]:
			k = 3 * i + 1 | 1
			sieve[k * k // 3::2 * k] = [False] * ((N // 6 - k * k // 6 - 1) // k + 1)
			sieve[(k * k + 4 * k - 2 * k * (i % 2)) // 3::2 * k] = [False] * ((N // 6 - (k * k + 4 * k - 2 * k * (i % 2)) // 6 - 1) // k + 1)
	return [2, 3] + [3 * i + 1 | 1 for i in range(1, N // 3 - correction) if sieve[i]]
p = primesbelow(5000)

def solve():
	n = N()
	b = lis()
	a = lis()
	temp = [(b[i], a[i]) for i in range(n)]
	temp.sort()
	t = temp[::-1]
	suff = [0]
	for i in t:
		suff.append(i[1] + suff[-1])
	suff = suff[::-1]
	m = suff[0]
	for i in range(n):
		t = max(temp[i][0], suff[i + 1])
		m = min(t, m)
	print(m)
testcase(int(inp()))


import os, operator, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for something in range(int(input())):
	n = int(input())
	a = []
	b = list(map(int, input().split()))
	c = list(map(int, input().split()))
	for i in range(n):
		a.append([b[i], c[i]])
	a.sort(key=operator.itemgetter(1))
	a.sort(key=operator.itemgetter(0), reverse=True)
	s = 0
	i = 0
	while i < n and s + a[i][1] < a[i][0]:
		s += a[i][1]
		i += 1
	if i == n:
		ans = s
	else:
		ans = max(s, a[i][0])
	os.sys.stdout.write(str(ans) + '\n')


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	c = [[a[i], b[i]] for i in range(n)]
	c.sort(key=lambda x: -x[0])
	a = [row[0] for row in c]
	b = [row[1] for row in c]
	l = 0
	r = n
	while r - l > 1:
		k = (r + l) // 2
		if a[k] > sum(b[:k]):
			l = k
		else:
			r = k
	print(min(a[l], sum(b[:l + 1])))


from sys import stdin, stdout

def INI():
	return int(stdin.readline())

def INL():
	return [int(_) for _ in stdin.readline().split()]

def INS():
	return stdin.readline()

def MOD():
	return pow(10, 9) + 7

def OPS(ans):
	stdout.write(str(ans) + '\n')

def OPL(ans):
	[stdout.write(str(_) + ' ') for _ in ans]
	stdout.write('\n')
for _ in range(INI()):
	n = INI()
	A = INL()
	B = INL()
	X = []
	for _ in range(n):
		X.append([A[_], B[_]])
	X.sort(reverse=True)
	s = 0
	ans = 0
	for _ in X:
		if s >= _[0]:
			pass
		else:
			ans += min(_[1], _[0] - s)
			s += min(_[1], _[0] - s)
	OPS(ans)


inp = [*open(0)]
for t in range(int(inp[0])):
	t *= 3
	N = int(inp[t + 1])
	if N == 1:
		print(min(int(inp[t + 2]), int(inp[t + 3])))
		continue
	a = list(map(int, inp[t + 2].split()))
	b = list(map(int, inp[t + 3].split()))
	c = sorted(list(zip(a, b)))
	(P, M) = (0, 0)
	for i in range(N - 1, -1, -1):
		if P + c[i][1] < c[i][0]:
			P += c[i][1]
		else:
			M = c[i][0]
			break
	print(max(P, M))


def check(a, b, n, m):
	c = 0
	for i in range(n):
		if a[i] <= m:
			continue
		c += b[i]
	return c <= m

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = 0
	r = 10 ** 10
	while l <= r:
		m = (l + r) // 2
		if check(a, b, n, m):
			r = m - 1
		else:
			l = m + 1
	return l
t = int(input())
i = 0
while i < t:
	print(solve())
	i += 1


def solve(n, a, b):
	res = []
	for i in range(n):
		res.append([a[i], b[i]])
	res.sort()
	sumb = sum(b)
	ans = sumb
	for i in range(n):
		ans = min(ans, max(res[i][0], sumb - res[i][1]))
		sumb -= res[i][1]
	return ans
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	print(solve(n, a, b))


t = int(input())
_ans = []
for _ in range(t):
	n = int(input())
	if n > 1:
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		dish = []
		for i in range(n):
			dish.append((a[i], b[i]))
		dish.sort(key=lambda x: x[0], reverse=1)
		_b = [dish[0][1]]
		for i in range(1, n):
			_b.append(_b[i - 1] + dish[i][1])
		ans = dish[0][0]
		dish.append((0, 0))
		for _ in range(n):
			i = _ + 1
			time = max(_b[i - 1], dish[i][0])
			if time < ans:
				ans = time
		_ans.append(ans)
	else:
		a = int(input())
		b = int(input())
		_ans.append(min(a, b))
print(str(_ans).replace(' ', '').replace('[', '').replace(']', '').replace(',', '\n'))


def binary(x):
	cur = 0
	for i in range(n):
		if a[i] > x:
			cur += b[i]
	return cur <= x
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	pairs = [[x, y] for (x, y) in zip(a, b)]
	pairs.sort(key=lambda x: x[0])
	l = 0
	r = 1000000000000.0
	while l + 1 < r:
		middle = (l + r) // 2
		if binary(middle):
			r = middle
		else:
			l = middle
	print(int(r))


for _ in range(int(input())):
	n = int(input())
	ls1 = [int(a) for a in input().split()]
	ls2 = [int(a) for a in input().split()]
	an = max(ls1)
	ls3 = []
	for i in range(n):
		ls3.append([ls1[i], ls2[i]])
	ls3.sort(reverse=True)
	wk = 0
	ls3.append([0, 0])
	for i in range(n):
		if ls3[i][0] > ls3[i][1] + wk:
			wk += ls3[i][1]
			an = max(ls3[i + 1][0], wk)
			if wk >= ls3[i][0]:
				break
		else:
			break
	print(an)


import sys
input = sys.stdin.readline
R = lambda : map(int, input().split())
(t,) = R()
for _ in [0] * t:
	R()
	s = 0
	ans = float('inf')
	for (x, y) in sorted(zip(R(), R()))[::-1]:
		ans = min(ans, max(x, s))
		s += y
	ans = min(ans, s)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = []
	for i in range(n):
		c.append((a[i], b[i]))
	c.sort(reverse=True)
	s = 0
	f = False
	for (x, y) in c:
		if s >= x:
			print(s)
			f = True
			break
		if y >= x:
			print(x)
			f = True
			break
		else:
			s += y
			if s >= x:
				print(x)
				f = True
				break
	if f == False:
		print(s)


t = int(input())
output = []
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = sorted(zip(a, b), key=lambda x: x[0])
	c.reverse()
	pick = 0
	if n == 1:
		output.append(str(min(c[0][0], c[0][1])))
	else:
		for i in range(n - 1):
			pick += c[i][1]
			if pick > c[i + 1][0]:
				output.append(str(min(c[i][0], pick)))
				break
			if i == n - 2:
				output.append(str(min(c[i + 1][0], pick + c[i + 1][1])))
print('\n'.join(output))


n = int(input())
toprint = []
for i in range(n):
	m = int(input())
	if m != 1:
		t1 = [int(q) for q in input().split()]
		t2 = [int(q) for q in input().split()]
		z = sorted(zip(t1, t2), reverse=True)
		(s, p) = (0, 0)
		for k in range(m):
			if z[k][0] > z[k][1] + s:
				s += z[k][1]
			else:
				p = max(p, z[k][0])
		toprint.append(max(p, s))
	else:
		toprint.append(min(int(input()), int(input())))
print('\n'.join(map(str, toprint)))


from sys import stdin
_input = stdin.readline
(_min, _list, _int, _max, _range) = (min, list, int, max, range)

def solution():
	for _ in _range(_int(_input())):
		n = _int(_input())
		arr_d = [_int(i) for i in _input().split()]
		arr_p = [_int(i) for i in _input().split()]
		index = _list(_range(n))
		index.sort(key=lambda x: (arr_d[x], -arr_p[x]), reverse=True)
		petr = 0
		if n == 1:
			print(_min(arr_d[0], arr_p[0]))
			continue
		for i in _range(n):
			if petr + arr_p[index[i]] < arr_d[index[i]]:
				petr += arr_p[index[i]]
			else:
				petr = _max(petr, arr_d[index[i]])
				break
		print(petr)
solution()


import sys
from collections import deque
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7

def resolve():
	t = int(input())
	for _ in range(t):
		n = int(input())
		A = list(map(int, input().split()))
		B = list(map(int, input().split()))
		que = deque(sorted([[a, b] for (a, b) in zip(A, B)], key=lambda x: [-x[0], x[1]]))
		res = [[que[0][0], 0]]
		tot = 0
		for i in range(n):
			(a, b) = que.popleft()
			tot += b
			ma = que[0][0] if que else 0
			res.append([ma, tot])
		ans = f_inf
		for (a, b) in res:
			ans = min(ans, max(a, b))
		print(ans)
resolve()


m = int(input())
ans_str = ''
for i in range(m):
	n = int(input())
	(a, b) = ([int(x) for x in input().split()], [int(y) for y in input().split()])
	s = [[x, y] for (x, y) in zip(a, b)]
	s.sort(key=lambda x: (-x[0], x[0]))
	A = B = 0
	ans = s[0][0]
	for j in range(n):
		A = s[j][0]
		time = max(A, B)
		if ans > time:
			ans = time
		B += s[j][1]
		if j == n - 1:
			time = B
			if ans > time:
				ans = time
	ans_str += str(ans) + '\n'
print(ans_str)


def delivery_dilemma(x, y, z):
	(delivery, pick) = zip(*sorted(list(zip(x, y))))
	s = sum(pick)
	for j in range(len(pick)):
		if delivery[j] >= s:
			z.append(s)
			break
		s -= pick[j]
		if delivery[j] >= s:
			z.append(delivery[j])
			break
t = int(input())
d = []
p = []
lt = []
for i in range(t):
	n = int(input())
	d.append(list(map(int, input().split())))
	p.append(list(map(int, input().split())))
for k in range(t):
	delivery_dilemma(d[k], p[k], lt)
for ans in lt:
	print(ans)


import sys
import itertools as it
import math as mt
import bisect as bi
import collections as cc
import itertools as it
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	(n,) = I()
	a = I()
	b = I()
	x = [[a[i], b[i]] for i in range(n)]
	x.sort(key=lambda x: x[0])
	for i in range(n - 2, -1, -1):
		x[i][1] += x[i + 1][1]
	ans = min(x[-1][0], x[0][1])
	for i in range(n - 1):
		ans = min(ans, max(x[i][0], x[i + 1][1]))
	print(ans)


import itertools
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	time = sorted(zip(a, b), key=lambda x: x[0])
	a = [a for (a, _) in time]
	b = [b for (_, b) in time]
	acc = list(itertools.accumulate(b[::-1]))[::-1] + [0]
	ans = acc[0]
	for i in range(len(a)):
		ans = min(ans, max(a[i], acc[i + 1]))
	print(ans)


from itertools import accumulate
for _ in range(int(input())):
	(n, delivery, pickup) = (int(input()), [*map(int, input().split())], [*map(int, input().split())])
	dp = sorted(zip(delivery, pickup))
	new_delivery = [i[0] for i in dp]
	new_pickup = [i[1] for i in dp]
	new_pickup_acc = [*accumulate(new_pickup)]
	ans = None
	all_delivered = max(delivery)
	all_picked = sum(pickup)
	for i in range(n):
		if ans == None:
			ans = max(new_delivery[i], new_pickup_acc[-1] - new_pickup_acc[i])
		else:
			x = max(new_delivery[i], new_pickup_acc[-1] - new_pickup_acc[i])
			ans = min(ans, x)
	print(min(ans, all_delivered, all_picked))


def time():
	pick = 0
	for v in comb:
		if v[0] >= v[1]:
			pick += v[1]
			if pick >= v[0]:
				return max(pick - v[1], v[0])
		else:
			return max(pick, v[0])
	return pick
for T in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	comb = [[a[i], b[i]] for i in range(n)]
	comb.sort(key=lambda x: x[0], reverse=True)
	print(time())


import sys

def input():
	return sys.stdin.readline()
for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	x = 10 ** 9
	y = 0
	while x > y + 1:
		z = (x + y) // 2
		t = 0
		for i in range(n):
			if A[i] > z:
				t += B[i]
		if t > z:
			y = z
		else:
			x = z
	print(x)


def get_ans(n, igrt, tp):
	td = 0
	ans = max(td, tp)
	for i in range(n):
		tdn = max(td, igrt[i][0])
		tpn = tp - igrt[i][1]
		if max(tdn, tpn) < ans:
			ans = max(tdn, tpn)
			td = tdn
			tp = tpn
	return ans
anss = []
t = int(input())
for _ in range(t):
	ni = int(input())
	ai = list(map(int, input().split()))
	bi = list(map(int, input().split()))
	integrated = list(zip(ai, bi))
	integrated.sort(key=lambda x: x[0] * 10 ** 10 + x[1])
	anss.append(get_ans(ni, integrated, sum(bi)))
for i in anss:
	print(i)


t = int(input())
(aa, bb) = ([], [])
for _ in range(t):
	input()
	ss = input().split()
	aa.append([int(s) for s in ss])
	ss = input().split()
	bb.append([int(s) for s in ss])

def get_sum(b, ind):
	res = 0
	for i in ind:
		res += b[i]
	return res
for i in range(t):
	indexes = sorted(range(len(aa[i])), key=lambda x: aa[i][x], reverse=True)
	cur_time = aa[i][indexes[0]]
	last_s = total_s = prev_j = 0
	for j in range(1, len(indexes)):
		if aa[i][indexes[j]] < cur_time:
			s = get_sum(bb[i], indexes[prev_j:j])
			total_s += s
			if total_s >= cur_time:
				print(max(last_s, cur_time))
				break
			cur_time = aa[i][indexes[j]]
			last_s = total_s
			prev_j = j
	else:
		total_s = last_s + get_sum(bb[i], indexes[prev_j:len(bb[i])])
		if total_s > cur_time:
			print(max(last_s, cur_time))
		else:
			print(total_s)


from sys import stdin, stdout
from collections import *
from math import gcd, floor, ceil
from bisect import bisect_left as bl
st = lambda : list(stdin.readline().strip())
li = lambda : list(map(int, stdin.readline().split()))
mp = lambda : map(int, stdin.readline().split())
inp = lambda : int(stdin.readline())
pr = lambda n: stdout.write(str(n) + '\n')
INF = float('inf')
mod = 1000000007

def solve():
	n = inp()
	l = li()
	k = li()
	z = list(zip(l, k))
	z.sort()
	s = sum(k)
	x = 0
	ans = INF
	for i in z:
		value = i[0]
		x += i[1]
		left = s - x
		ans = min(ans, value + max(left - value, 0))
	p = sum(l)
	h = list(zip(k, l))
	x = 0
	val = 0
	for i in h:
		x += i[0]
		val += i[1]
		left = p - val
		ans = min(ans, x + max(left - x, 0))
	pr(ans)
for _ in range(inp()):
	solve()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
for _ in range(int(ri())):
	n = int(ri())
	a = Ri()
	b = Ri()
	ans = 0
	lis = []
	for i in range(n):
		lis.append((b[i], a[i]))
	lis.sort(key=lambda x: (-x[1], x[0]))
	if len(lis) == 0:
		print(ans)
		continue
	ans = lis[0][1]
	summ = 0
	for i in range(len(lis) - 1):
		summ += lis[i][0]
		ans = min(ans, max(summ, lis[i + 1][1]))
	summ = 0
	for i in range(len(lis)):
		summ += lis[i][0]
	ans = min(ans, summ)
	print(ans)


import math
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	s = sum(b)
	l = []
	ans = max(a)
	for i in range(n):
		l.append((a[i], b[i]))
	l.sort()
	cnt = 0
	i = len(l) - 1
	f = 0
	while i > -1:
		tans = l[i][0]
		cnt = cnt + l[i][1]
		if cnt <= tans:
			if i == 0:
				ans = s
			else:
				ans = l[i - 1][0]
		else:
			cnt = cnt - l[i][1]
			break
		i -= 1
	print(max(ans, cnt))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ord = []
	for i in range(n):
		ord.append([a[i], b[i]])
	ord = sorted(ord, reverse=True)
	ans = 0
	time = 0
	ans = 0
	summ = ans
	for i in range(n):
		if ord[i][0] >= ans + ord[i][1]:
			ans = ans + ord[i][1]
		else:
			ans = max(ord[i][0], ans)
			break
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = [[a[i], b[i]] for i in range(n)]
	c.sort(key=lambda x: x[0])
	min = 0
	for i in range(n):
		min += c[i][1]
	kek = min
	k = 0
	for i in range(n):
		k += c[i][1]
		if min >= max(c[i][0], kek - k):
			min = max(c[i][0], kek - k)
	print(min)


for _ in range(int(input())):
	n = int(input())
	A = [int(x) for x in input().split()]
	B = [int(x) for x in input().split()]
	K = sorted(zip(A, B))
	result = sum(B)
	ans = result
	for i in K:
		result -= i[1]
		ans = min(ans, max(i[0], result))
	print(ans)


import sys
try:
	(sys.stdin, sys.stdout) = (open('in.txt', 'r'), open('out.txt', 'w'))
except:
	pass
ii1 = lambda : int(sys.stdin.readline().strip())
is1 = lambda : sys.stdin.readline().strip()
iia = lambda : list(map(int, sys.stdin.readline().strip().split()))
isa = lambda : sys.stdin.readline().strip().split()
mod = int(1000000000.0 + 7)
from collections import *
from math import *
from itertools import *
for _ in range(ii1()):
	n = ii1()
	a = iia()
	b = iia()
	arr = []
	for i in range(n):
		arr.append([a[i], b[i]])
	arr.sort(reverse=True)
	pre = []
	s = 0
	for i in range(n):
		s += arr[i][1]
		pre.append(s)
	suff = []
	ss = 0
	for i in range(n - 1, -1, -1):
		ss = max(ss, arr[i][0])
		suff.append(ss)
	suff = suff[::-1]
	ans = max(suff)
	for i in range(n - 1):
		ans = min(ans, max(pre[i], suff[i + 1]))
	ans = min(ans, pre[-1])
	print(ans)


import sys
from array import array
from typing import List, Tuple, TypeVar, Generic, Sequence, Union

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def main():
	t = int(input())
	ans = [''] * t
	for i in range(t):
		n = int(input())
		a = tuple(map(int, input().split()))
		b = tuple(map(int, input().split()))
		(ok, ng) = (10 ** 9, 0)
		while abs(ok - ng) > 1:
			mid = ok + ng >> 1
			time = 0
			for j in range(n):
				if a[j] > mid:
					time += b[j]
			if time <= mid:
				ok = mid
			else:
				ng = mid
		ans[i] = str(ok)
	sys.stdout.buffer.write('\n'.join(ans).encode('utf-8'))
main()


import sys, os
from math import sqrt, gcd, ceil, log, floor
from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
input = sys.stdin.readline
read = lambda : list(map(int, input().strip().split()))
MOD = 10 ** 9 + 7

def main():
	ans_ = ''
	for _ in range(int(input())):
		n = int(input())
		a = read()
		b = read()
		arr = [(-i, j) for (i, j) in zip(a, b)]
		heapify(arr)
		ans = 0
		s = 0
		while arr and s + arr[0][1] < -arr[0][0]:
			s += arr[0][1]
			t = heappop(arr)
		if arr:
			ans = max(-heappop(arr)[0], s)
		else:
			ans = s
		ans_ += str(ans) + '\n'
	print(ans_)
main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	p = []
	for i in range(n):
		p.append((a[i], b[i]))
	p.sort(reverse=True)
	m = p[-1][0]
	s = 0
	for i in range(n):
		if s + p[i][1] <= p[i][0]:
			s += p[i][1]
			m = s
		else:
			m = max(p[i][0], s)
			break
	print(m)


try:
	t = int(input())
	for i in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		pair = []
		for i in range(len(a)):
			pair.append([a[i], b[i]])
		pair = sorted(pair)
		stack = []
		stack.append(pair[0])
		for i in range(1, len(pair)):
			if stack[-1][0] == pair[i][0]:
				stack[-1][1] += pair[i][1]
			else:
				stack.append(pair[i])
		prefix = [0] * len(stack)
		prefix[-1] = stack[-1][1]
		for i in range(len(stack) - 2, -1, -1):
			prefix[i] = prefix[i + 1] + stack[i][1]
		maxi = []
		for i in range(len(stack) - 1):
			maxi.append(max(stack[i][0], prefix[i + 1]))
		maxi.append(stack[-1][0])
		maxi.append(prefix[0])
		res = min(maxi)
		print(res)
except:
	pass


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	del_pic = {}
	for i in range(n):
		if a[i] in del_pic:
			del_pic[a[i]].append(b[i])
		else:
			del_pic[a[i]] = [b[i]]
	total_pic = sum(b)
	h = max(a)
	pre_sm = 0
	m = []
	for j in del_pic:
		m.append(j)
	m.sort()
	for i in m:
		k = i
		pre_sm += sum(del_pic[i])
		rem = total_pic - pre_sm
		h = min(h, max(k, rem))
	print(min(sum(b), h))


def get_fastest_schedule_time(a, b):
	sorted_dishes = sorted(zip(a, b), reverse=True)
	take_time = 0
	last_taken = -1
	for (i, ab) in enumerate(sorted_dishes):
		(aa, bb) = ab
		if take_time + bb < aa:
			take_time += bb
			last_taken = i
		else:
			break
	if last_taken == len(sorted_dishes) - 1:
		return take_time
	return max(take_time, sorted_dishes[last_taken + 1][0])
n_samples = int(input())
for t in range(n_samples):
	n = int(input())
	a = list(map(int, input().split(' ')))
	b = list(map(int, input().split(' ')))
	print(get_fastest_schedule_time(a, b))


for y in range(int(input())):
	n = int(input())
	lst1 = list(map(int, input().split()))
	lst2 = list(map(int, input().split()))
	lst = [0] * n
	for i in range(n):
		lst[i] = [lst1[i], lst2[i]]
	lst.sort()
	ans = sum(lst2)
	minn = ans
	for i in range(n):
		ans = ans - lst[i][1]
		minn = min(max(lst[i][0], ans), minn)
	print(minn)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	k = list(map(int, input().split()))
	zipp = list(zip(l, k))
	zipp.sort()
	s = sum(k)
	x = 0
	anss = float('inf')
	for i in zipp:
		v = i[0]
		x += i[1]
		left = s - x
		anss = min(anss, v + max(left - v, 0))
	p = sum(l)
	hpp = list(zip(k, l))
	x = 0
	w = 0
	for i in hpp:
		x += i[0]
		w += i[1]
		left = p - w
		anss = min(anss, x + max(left - x, 0))
	print(anss)


import sys
import math
from collections import Counter
input = sys.stdin.readline
N = 1000000007
for _ in range(int(input().strip())):
	n = int(input().strip())
	a = [int(j) for j in input().strip().split()]
	b = [int(j) for j in input().strip().split()]
	x = []
	for i in range(n):
		x.append([a[i], b[i]])
	x.sort()
	time1 = 0
	for i in range(n - 1, -1, -1):
		if x[i][0] - x[i][1] > time1:
			time1 = time1 + x[i][1]
			time = time1
		else:
			time = time1 if time1 > x[i][0] else x[i][0]
			break
	print(time)


t = int(input())
while t != 0:
	n = int(input())
	list1 = list(map(int, input().split()))
	list2 = list(map(int, input().split()))
	list3 = []
	for i in range(n):
		list3.append([list1[i], list2[i]])
	list3.sort(key=lambda x: x[0])
	ans = list3[-1][0]
	i = n - 2
	temp = 0
	while i >= 0:
		temp += list3[i + 1][1]
		if max(list3[i][0], temp) < ans:
			ans = max(list3[i][0], temp)
		i -= 1
	ans = min(ans, sum(list2))
	print(ans)
	t -= 1


import sys
input = sys.stdin.readline
from collections import defaultdict
t = int(input())
for i in range(t):
	n = int(input())
	a = [int(i) for i in input().split() if i != '\n']
	b = [int(i) for i in input().split() if i != '\n']
	dicta = defaultdict(list)
	for i in range(n):
		dicta[a[i]].append(b[i])
	(ans, store) = ([], 0)
	a.sort(reverse=True)
	a.append(0)
	ans.append(a[0])
	for i in range(n):
		mina = min(dicta[a[i]])
		if mina < a[i]:
			store += mina
			dicta[a[i]].remove(mina)
			ans.append(max(store, a[i + 1]))
		else:
			break
	sys.stdout.write(str(min(ans)) + '\n')


import sys
tests = int(sys.stdin.readline())
for _ in range(tests):
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	b = list(map(int, sys.stdin.readline().split()))
	speedup = [(a[x] - b[x], a[x], b[x]) for x in range(n)]
	speedup.sort(key=lambda x: x[1], reverse=True)
	minute = 0
	to_order = []
	for dish in speedup:
		if dish[0] > 0 and minute + dish[2] < dish[1]:
			minute += dish[2]
		else:
			to_order.append(dish[1])
	max_wait = max(to_order) if to_order else 0
	print(max(minute, max_wait))


import sys
from copy import *
from bisect import *
from math import gcd, ceil, sqrt
from itertools import permutations as prm, product

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')
di = [[-1, 0], [1, 0], [0, 1], [0, -1]]

def string(s):
	return ''.join(s)

def fori(n):
	return [fi() for i in range(n)]

def inc(d, c, x=1):
	d[c] = d[c] + x if c in d else x

def bo(i):
	return ord(i) - ord('A')

def li():
	return [int(xx) for xx in input().split()]

def fli():
	return [float(x) for x in input().split()]

def comp(a, b):
	if a > b:
		return 2
	return 2 if a == b else 0

def gi():
	return [xx for xx in input().split()]

def cil(n, m):
	return n // m + int(n % m > 0)

def fi():
	return int(input())

def pro(a):
	return reduce(lambda a, b: a * b, a)

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def isvalid(i, j, n, m):
	return 0 <= i < n and 0 <= j < m

def bo(i):
	return ord(i) - ord('a')

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)
t = fi()
while t > 0:
	t -= 1
	n = fi()
	a = li()
	b = li()
	l = ans = 0
	r = 10 ** 15

	def can(mid):
		c = 0
		for i in range(n):
			if a[i] <= mid:
				continue
			c += b[i]
		return c <= mid
	while l <= r:
		mid = (l + r) // 2
		if can(mid):
			ans = mid
			r = mid - 1
		else:
			l = mid + 1
	print(ans)


rn = lambda : int(input())
rl = lambda : list(map(int, input().split()))
rns = lambda : map(int, input().split())
rs = lambda : input()
yn = lambda x: print('Yes') if x else print('No')
YN = lambda x: print('YES') if x else print('NO')
for _ in range(rn()):
	n = rn()
	a = rl()
	b = rl()
	l = [[a[i], b[i]] for i in range(n)]
	l.sort()
	pre = [0]
	for i in range(n - 1, -1, -1):
		pre.append(pre[-1] + l[i][1])
	pre.pop(0)
	pre = pre[::-1]
	ans = l[-1][0]
	for i in range(n - 1):
		ans = min(max(l[i][0], pre[i + 1]), ans)
	print(min(ans, pre[0]))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	arr = [None] * n
	for i in range(n):
		arr[i] = [a[i], b[i]]
	arr.sort(key=lambda a: a[0], reverse=True)
	res = arr[0][0]
	arr.append([0, 0])
	currSum = 0
	for i in range(n):
		currSum += arr[i][1]
		res = min(res, max(arr[i + 1][0], currSum))
	print(res)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	b.append(0)
	aa = []
	bb = []
	for i in range(len(a)):
		aa.append((a[i], i))
	aa.sort(key=lambda x: x[0])
	aa.append((0, n))
	min_t = 999999999999
	s = 0
	for i in range(n - 1, -2, -1):
		tmp = 0
		if i != -1:
			time = aa[i][0]
			s += b[aa[i + 1][1]]
			if s > time:
				time += s - time
		else:
			time = sum(b)
		min_t = min(min_t, time)
	print(min_t)


def read_generator():
	while True:
		tokens = input().split(' ')
		for t in tokens:
			yield t
reader = read_generator()

def readword():
	return next(reader)

def readint():
	return int(next(reader))

def readfloat():
	return float(next(reader))

def readline():
	return input()

def solve(a, b, n):
	l = 1
	r = 10 ** 9
	while r - l > 1:
		t = (l + r) // 2
		if possible(a, b, n, t):
			r = t
		else:
			l = t
	if possible(a, b, n, l):
		return l
	return r

def possible(a, b, n, t):
	s = 0
	for i in range(n):
		if a[i] > t:
			s += b[i]
	return s <= t
tests = readint()
for t in range(tests):
	n = readint()
	a = [readint() for _ in range(n)]
	b = [readint() for _ in range(n)]
	print(solve(a, b, n))


n = int(input())
s = [[int(input()), list(map(int, input().split())), list(map(int, input().split()))] for i in range(n)]
w = []
m = []
for x in range(n):
	ww = []
	p = 0
	for y in range(s[x][0]):
		ww.append([s[x][1][y], s[x][2][y]])
	ww = sorted(ww + [[0, 0]], key=lambda m: -m[0])
	for z in range(s[x][0]):
		p += ww[z][1]
		if p >= ww[z + 1][0]:
			m.append(min(p, ww[z][0]))
			break
print('\n'.join(map(str, m)))


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	sorted_multi_list = sorted(list(zip(a, b)), key=lambda x: (-x[0], x[0]))
	your_turn_time = 0
	for (their, you) in sorted_multi_list:
		if your_turn_time + you < their:
			your_turn_time += you
		else:
			print(max(your_turn_time, their))
			break
	else:
		print(your_turn_time)


from collections import defaultdict as dft, deque, Counter
from heapq import heappush, heappop

def mp():
	return map(int, input().split())

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

def solve():

	def chk(x):
		total = 0
		for i in range(n):
			if a[i] > x:
				total += b[i]
		return total <= x
	n = int(input())
	a = ml()
	b = ml()
	lo = 1
	hi = max(a)
	res = hi
	while lo <= hi:
		mid = (lo + hi) // 2
		if chk(mid):
			res = mid
			hi = mid - 1
		else:
			lo = mid + 1
	print(res)
tc = int(input())
for _ in range(tc):
	solve()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	t = []
	for i in range(n):
		t.append([a[i], b[i]])
	t.sort()
	cnt = 0
	ans = t[-1][0]
	check = False
	for i in range(n - 1, -1, -1):
		if t[i][1] < t[i][0]:
			cnt += t[i][1]
			if cnt >= ans:
				cnt -= t[i][1]
				break
			if i >= 0:
				ans = t[i - 1][0]
		else:
			break
	print(max(min(ans, sum(b)), cnt))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline()

def RL():
	return map(int, sys.stdin.readline().split())

def RLL():
	return list(map(int, sys.stdin.readline().split()))

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
from math import ceil, floor, sqrt, pow
for _ in range(N()):
	n = N()
	a = RLL()
	b = RLL()
	l = []
	for i in range(n):
		l.append([a[i], b[i]])
	l.sort(key=lambda x: x[0])
	c = l[-1][0]
	p = 0
	for i in range(n - 1, -1, -1):
		p += l[i][1]
		if i != 0:
			a = max(l[i - 1][0], p)
			c = min(c, a)
		else:
			a = p
			c = min(c, a)
	print(c)


t = int(input())
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split(' ')))
	b = list(map(int, input().split(' ')))
	c = []
	for i in range(n):
		c.append([a[i], b[i]])
	c.sort()
	c.reverse()
	ans = 10000000000000000
	pref = []
	for i in range(n):
		pref.append(0)
	pref[0] = c[0][1]
	for i in range(1, n):
		pref[i] = pref[i - 1] + c[i][1]
	pref.reverse()
	c.reverse()
	maxi = 0
	for i in range(n - 1):
		maxi = max(maxi, c[i][0])
		ans = min(ans, max(pref[i + 1], maxi))
	maxi = max(maxi, c[n - 1][0])
	ans = min(ans, pref[0])
	ans = min(ans, maxi)
	print(ans)


t = int(input())
for t1 in range(0, t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	s = sum(b)
	l = list(zip(a, b))
	l = sorted(l, key=lambda x: (-x[0], x[1]))
	mx = []
	mx.append(l[-1][0])
	for i in range(n - 2, -1, -1):
		mx.append(max(mx[-1], l[i][0]))
	mx = mx[::-1]
	s1 = 0
	ans = max(sum(a), sum(b))
	for i in range(0, len(l)):
		s1 += l[i][1]
		if i == n - 1:
			ans = min(ans, max(s1, mx[i]))
		elif i == 0:
			if i + 1 < n:
				ans = min(ans, max(s1, mx[i + 1]))
			else:
				ans = min(ans, min(s1, mx[i]))
		else:
			ans = min(ans, max(s1, mx[i + 1]))
	ans = min(max(a), sum(b), ans)
	print(ans)


import sys
input = sys.stdin.readline
from operator import itemgetter
t = int(input())
for tests in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	SUM = 0
	X = []
	for i in range(n):
		X.append((A[i], B[i]))
		SUM += B[i]
	X.sort(key=itemgetter(0))
	S = [0] * (n + 1)
	for i in range(n - 1, -1, -1):
		S[i] = X[i][1] + S[i + 1]
	ANS = min(SUM, max(A))
	for i in range(n):
		ANS = min(ANS, max(X[i][0], S[i + 1]))
	print(ANS)


t = int(input())
ans = []
for _ in range(t):
	dishes = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	picktime = sum(b)
	l1 = sorted(zip(a, b))
	for k in range(dishes):
		delivery = l1[k][0]
		if picktime > delivery:
			picktime -= l1[k][1]
			picktime = max(delivery, picktime)
	ans.append(picktime)
for _ in ans:
	print(_)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = [(a[i], b[i]) for i in range(n)]
	c.sort(key=lambda x: (x[0], -x[1]))
	maxa = [c[i][0] for i in range(n)]
	for i in range(1, n):
		maxa[i] = max(c[i][0], maxa[i - 1])
	sumb = [c[i][1] for i in range(n)]
	sumb.append(0)
	for i in range(n - 1, -1, -1):
		sumb[i] = sumb[i + 1] + c[i][1]
	mincost = float('inf')
	for i in range(n):
		mincost = min(mincost, max(maxa[i], sumb[i + 1]))
	mincost = min(mincost, sumb[0])
	print(mincost)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	left = []
	amax = 0
	for j in range(n):
		if a[j] > b[j]:
			left.append([a[j], b[j]])
		elif a[j] > amax:
			amax = a[j]
	c = 0
	for j in list(reversed(sorted(left))):
		if c + j[1] <= j[0]:
			c += j[1]
		else:
			if amax < j[0]:
				amax = j[0]
			break
	if len(a) == 0:
		print(c)
	else:
		print(max(amax, c))


from sys import stdin
input = stdin.readline
from itertools import accumulate
t = int(input())
for _ in range(t):
	n = int(input())
	delivery = list(map(int, input().split()))
	person = list(map(int, input().split()))
	a = []
	pf = [0]
	sm = sum(person)
	for i in range(n):
		a.append((delivery[i], person[i]))
	a.sort()
	for i in range(n):
		pf.append(pf[-1] + a[i][1])
	ans = sm
	for i in range(n):
		ans = min(ans, max(a[i][0], sm - pf[i + 1]))
	print(ans)


import sys
import math
from collections import defaultdict, Counter
input = sys.stdin.readline

def print(x):
	sys.stdout.write(str(x) + '\n')
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = []
	for (a1, b1) in zip(a, b):
		l.append([a1, b1])
	l.sort(reverse=True)
	a1 = l[0][0]
	b1 = 0
	top = 1
	while a1 > b1 and top <= n:
		if top < n:
			a1 = l[top][0]
		b1 += l[top - 1][1]
		top += 1
	print(min(l[top - 2][0], b1))


import typing
import sys
import math
import collections
import bisect
import itertools
import heapq
import decimal
import copy
INF = 10 ** 20
MOD = 10 ** 9 + 7

def ni():
	return int(sys.stdin.buffer.readline())

def ns():
	return map(int, sys.stdin.buffer.readline().split())

def na():
	return list(map(int, sys.stdin.buffer.readline().split()))

def na1():
	return list(map(lambda x: int(x) - 1, sys.stdin.buffer.readline().split()))

def main():
	t = ni()
	for i in range(t):
		n = ni()
		a = na()
		b = na()
		table = [[a[i], b[i]] for i in range(n)]
		table.sort()
		bcum = [0] * (n + 1)
		for i in range(1, n + 1):
			bcum[i] = bcum[i - 1] + table[-i][1]
		ans = bcum[-1]
		for i in range(n):
			tans = max(table[i][0], bcum[n - i - 1])
			ans = min(ans, tans)
		print(ans)
main()


import sys
from collections import deque, defaultdict, namedtuple
import heapq
from math import sqrt, factorial, gcd, ceil, atan, pi
from itertools import permutations

def input():
	return sys.stdin.buffer.readline().decode('utf-8').strip()
import string
import operator
import random
from bisect import bisect_left, bisect_right
from functools import lru_cache, reduce
MOD = int(1000000000.0) + 7
INF = float('inf')

def solve():
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	c = list(zip(a, b))
	c.sort(key=lambda x: -x[0])
	cur = 0
	for (x, y) in c:
		if cur + y < x:
			cur += y
		else:
			print(max(cur, x))
			return
	print(cur)
T = 1
T = int(input())
for case in range(1, T + 1):
	ans = solve()


T = int(input())
to_print = []
while T:
	T -= 1
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	if n == 1:
		to_print.append(min(a[0], b[0]))
		continue
	ab = list(zip(a, b))
	ab.sort(key=lambda x: (-x[0], x[1]))
	for i in range(1, n):
		ab[i] = (ab[i][0], ab[i][1] + ab[i - 1][1])
	to_print.append(max(map(min, ab)))
else:
	print('\n'.join(map(str, to_print)))


from sys import stdin
input = stdin.readline
t = int(input())
for i in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	arr = []
	for i in range(n):
		arr.append((a[i], b[i]))
	arr.sort()
	s = []
	x = 0
	for i in range(n):
		x = x + arr[i][1]
		s.append(x)
	ans = 100000000000000000
	for i in range(n):
		ans = min(ans, max(x - s[i], arr[i][0]))
	ans = min(ans, x)
	ans = min(ans, arr[-1][0])
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	new = [0] * n
	for i in range(n):
		new[i] = (a[i], b[i])
	prefS = [0] * (n + 1)
	new.sort()
	for i in range(n - 1, -1, -1):
		prefS[i] = prefS[i + 1] + new[i][1]
	m = prefS[0]
	for i in range(n):
		m = min(max(new[i][0], prefS[i + 1]), m)
	print(m)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().strip().split()))
	b = list(map(int, input().strip().split()))
	c = [(a[i], b[i]) for i in range(n)]
	c.sort(reverse=True)
	z = 0
	for i in range(n):
		(x, y) = c[i]
		if x > y and y + z < x:
			z += y
		else:
			z = max(z, x)
			break
	print(z)


import math

def readGenerator():
	while True:
		tokens = input().split(' ')
		for t in tokens:
			yield t
reader = readGenerator()

def readWord():
	return next(reader)

def readInt():
	return int(next(reader))

def readFloat():
	return float(next(reader))

def readLine():
	return input()

def fact(n):
	f = 1
	for i in range(1, n + 1):
		f *= i
	return f

def solve(n, a, b):
	m = []
	for i in range(n):
		m.append([a[i], b[i]])
	m.sort(reverse=True)
	ans = min(sum(b), max(a))
	s = 0
	for i in range(n):
		s += m[i][1]
		ma = m[i + 1][0] if i < n - 1 else 0
		ans = min(ans, max(s, ma))
	return ans
t = readInt()
for i in range(t):
	n = readInt()
	a = [readInt() for _ in range(n)]
	b = [readInt() for _ in range(n)]
	print(solve(n, a, b))


def helper(m):
	s = 0
	for i in range(len(a)):
		if a[i] > m:
			s += b[i]
	return s <= m
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	(l, r) = (1, 10 ** 9)
	while l < r:
		mid = l + (r - l) // 2
		temp = helper(mid)
		if temp:
			r = mid
		else:
			l = mid + 1
	print(l)


an = []
t = int(input())
for i in range(t):
	n = int(input())
	if n == 1:
		a = int(input())
		b = int(input())
		if a == b:
			an.append(a)
		else:
			an.append(min(a, b))
	else:
		a = [int(x) for x in input().split()]
		b = [int(x) for x in input().split()]
		dish = list(zip(a, b))
		dish.sort(key=lambda x: x[0])
		if min(b) > dish[-1][0]:
			an.append(dish[-1][0])
		else:
			s = sum(b)
			ans = min(dish[-1][0], s)
			if dish[0][0] < s:
				for d in dish:
					s -= d[1]
					time = max(d[0], s)
					ans = min(ans, time)
			an.append(ans)
for i in range(t):
	print(an[i])


t = int(input())
for c in range(t):
	n = int(input())
	a = [int(x) for x in input().strip().split(' ')]
	b = [int(x) for x in input().strip().split(' ')]
	cost_pair = list(zip(a, b))
	cost_pair.sort(reverse=True)
	cur_p = 0
	i = 0
	while len(cost_pair) > i:
		next_dev = cost_pair[i]
		r_dev = next_dev[0]
		p_dev = next_dev[1]
		if cur_p + p_dev <= r_dev:
			i += 1
			cur_p += p_dev
		else:
			break
	if len(cost_pair) > i:
		print(max(cur_p, cost_pair[i][0]))
	else:
		print(cur_p)


import itertools
import math
import sys
import os
from collections import defaultdict

def is_debug():
	return 'PYPY3_HOME' not in os.environ

def stdin_wrapper():
	data = '4\n4\n3 7 4 5\n2 1 2 4\n4\n1 2 3 4\n3 3 3 3\n2\n1 2\n10 10\n2\n10 10\n1 2\n'
	for line in data.split('\n'):
		yield line
if not is_debug():

	def stdin_wrapper():
		while True:
			yield sys.stdin.readline()
inputs = stdin_wrapper()

def input_wrapper():
	return next(inputs)

def get_str():
	if is_debug():
		return input_wrapper()
	return input()

def get(_type):
	if _type == str:
		return get_str()
	return _type(input_wrapper())

def get_arr(_type):
	return [_type(x) for x in input_wrapper().split()]

def tuplerize(method):

	def wrap(*args, **kwargs):
		res = method(*args, **kwargs)
		if not isinstance(res, (tuple, list)):
			res = (res,)
		return res
	return wrap

@tuplerize
def solve(a, b):
	x = list(zip(a, b))
	x = sorted(x, key=lambda el: (-el[0], el[1]))
	pref = [0 for _ in range(len(x) + 1)]
	s = 0
	for i in range(len(x)):
		pref[i] = s
		s += x[i][1]
	pref[-1] = s
	res = float('inf')
	for i in range(len(x)):
		res = min(res, max(x[i][0], pref[i]))
	res = min(res, sum((w for (_, w) in x)))
	return res
t = get(int)
for _ in range(t):
	n = get(int)
	a = get_arr(int)
	b = get_arr(int)
	print(*solve(a, b))


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	br = list(map(int, input().split()))
	li = []
	for i in range(n):
		li.append([ar[i], br[i]])
	li.sort(key=lambda x: x[0])
	ma = []
	su = []
	p1 = 0
	p2 = 0
	for i in range(n):
		p1 = max(p1, li[i][0])
		ma.append(p1)
	for i in range(1, n + 1):
		p2 += li[-i][1]
		su.append(p2)
	su = su[::-1]
	su.append(0)
	ans = su[0]
	for i in range(n):
		ans = min(ans, ma[i] + max(su[i + 1] - ma[i], 0))
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	zipLst = sorted(list(zip(a, b)), reverse=True)
	_sum = 0
	high = 0
	for i in range(n):
		if zipLst[i][1] + _sum <= zipLst[i][0]:
			_sum += zipLst[i][1]
		else:
			high = max(high, zipLst[i][0])
	print(max(high, _sum))


def solve():
	n = int(input())
	a = [*map(int, input().split())]
	b = [*map(int, input().split())]
	c = [(a[i], b[i]) for i in range(n)]
	c.sort()
	S = [0 for _ in range(n)]
	_sum = 0
	for i in range(n - 1, -1, -1):
		_sum += c[i][1]
		S[i] = _sum
	res = sum(b)
	for i in range(0, n):
		tmp = c[i][0]
		if i + 1 < n:
			tmp = max(tmp, S[i + 1])
		res = min(tmp, res)
	print(res)
t = int(input())
for i in range(t):
	solve()


input = __import__('sys').stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(n):
		a[i] = (a[i], b[i])
	a.sort(reverse=True)
	total = 0
	ans = 0
	for i in range(n):
		if total + a[i][1] < a[i][0]:
			total += a[i][1]
		else:
			ans = a[i][0]
			break
	print(max(ans, total))


import sys
t = int(sys.stdin.readline())
for _ in range(t):
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	b = list(map(int, sys.stdin.readline().split()))
	if n == 1:
		sys.stdout.write('{}\n'.format(min(a[0], b[0])))
	else:
		c = sorted(list(zip(a, b)), reverse=True)
		b_time = 0
		for i in range(n):
			b_time += c[i][1]
			if b_time >= c[i][0]:
				b_time = max(c[i][0], b_time - c[i][1])
				break
		sys.stdout.write('{}\n'.format(b_time))


l = []
for i in range(int(input())):
	n = int(input()) - 1
	ab = sorted([*zip([*map(int, input().split())], [*map(int, input().split())])])
	s = 0
	while s < ab[n][0] and n > -1:
		s += ab[n][1]
		n -= 1
	l.append(min(s, ab[n + 1][0]))
print('\n'.join(map(str, l)))


import sys, math, cmath, time
start_time = time.time()

def solve():
	n = inp()
	a = inlt()
	b = inlt()
	q = [[a[i], b[i]] for i in range(len(a))]
	w = list(set(a)) + [0]
	w.sort()
	q.sort(reverse=True)
	qw = [max(a)]
	c = 0
	i = 0
	while i < len(q):
		while i < len(q) and q[i][0] == w[-1]:
			c = c + q[i][1]
			i = i + 1
		qw.append(max(c, w[-2]))
		w.pop()
	print(min(qw))

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(1, t + 1):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

def inp():
	return int(input())

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

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

def invr():
	return map(int, input().split())

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def counter_elements(a):
	q = dict()
	for i in range(len(a)):
		if a[i] not in q:
			q[a[i]] = 0
		q[a[i]] = q[a[i]] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q

def factorial(n, m=1000000007):
	q = 1
	for i in range(n):
		q = q * (i + 1) % m
	return q

def factors(n):
	q = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			q.append(i)
			q.append(n // i)
	return list(sorted(list(set(q))))

def prime_factors(n):
	q = []
	while n % 2 == 0:
		q.append(2)
		n = n // 2
	for i in range(3, int(n ** 0.5) + 1, 2):
		while n % i == 0:
			q.append(i)
			n = n // i
	if n > 2:
		q.append(n)
	return list(sorted(q))

def transpose(a):
	(n, m) = (len(a), len(a[0]))
	b = [[0] * n for i in range(m)]
	for i in range(m):
		for j in range(n):
			b[i][j] = a[j][i]
	return b

def power_two(x):
	return x and (not x & x - 1)

def ceil(a, b):
	return -(-a // b)

def seive(n):
	a = [1]
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p ** 2, n + 1, p):
				prime[i] = False
		p = p + 1
	for p in range(2, n + 1):
		if prime[p]:
			a.append(p)
	return a

def ncr(n, r):
	return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

def npr(n, r):
	return math.factorial(n) // math.factorial(n - r)
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase

def main():

	def condition(x):
		time = 0
		for (courier_time, self_time) in zip(courier, Self):
			if courier_time > x:
				time += self_time
		return time <= x
	for _ in range(int(input())):
		n = int(input())
		courier = list(map(int, input().split()))
		Self = list(map(int, input().split()))
		(left, right) = (0, max(courier))
		ans = right
		while left <= right:
			mid = (left + right) // 2
			if condition(mid):
				ans = mid
				right = mid - 1
			else:
				left = mid + 1
		print(ans)
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()
for _ in range(II()):
	n = II()
	aa = LI()
	bb = LI()

	def ok(m):
		s = 0
		for (a, b) in zip(aa, bb):
			if a > m:
				s += b
		return s <= m
	(l, r) = (0, 10 ** 9)
	while l + 1 < r:
		m = (l + r) // 2
		if ok(m):
			r = m
		else:
			l = m
	print(r)


import sys
ans = []
for _ in range(int(sys.stdin.readline())):
	sys.stdin.readline()
	a = [*map(int, sys.stdin.readline().split())]
	b = [*map(int, sys.stdin.readline().split())]
	ab = sorted([*zip(a, b)], reverse=True)
	time = 0
	for z in ab:
		deli = z[0]
		pick = z[1]
		time += pick
		if time >= deli:
			time = max(deli, time - pick)
			break
	ans.append(str(time))
print('\n'.join(ans))


for _ in range(int(input())):
	n = int(input())
	c = []
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(n):
		c.append([a[i], b[i]])
	c.sort(reverse=True)
	su = [c[0][1]] * n
	for i in range(1, n):
		su[i] = c[i][1] + su[i - 1]
	ans = min(max(a), su[-1])
	for i in range(n - 1):
		ans = min(ans, max(su[i], c[i + 1][0]))
	print(ans)


def do():
	import itertools
	squery = lambda a, b: sdat[b + 1] - sdat[a]
	n = int(input())
	data = list(map(int, input().split()))
	datb = list(map(int, input().split()))
	dat = []
	for i in range(n):
		dat.append([data[i], datb[i]])
	dat.sort()
	dat.append([0, 0])
	l = []
	for i in range(n + 1):
		l.append(dat[i][1])
	sdat = list(itertools.accumulate(itertools.chain([0], l)))
	res = 10 ** 18
	for i in range(n):
		res = min(res, max(dat[i][0], squery(i + 1, n)))
	print(min(res, sum(datb)))
q = int(input())
for _ in range(q):
	do()


import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcdefghijklmnopqrstuvwxyz/'
M = 1000000007
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	n = Int()
	a = array()
	b = array()
	a = [(a[i], b[i]) for i in range(n)]
	a.sort()
	pre = [0] * n
	for i in range(n - 2, -1, -1):
		pre[i] = pre[i + 1] + a[i + 1][1]
	ans = pre[0] + a[0][1]
	for i in range(n):
		ans = min(max(a[i][0], pre[i]), ans)
	print(ans)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	b = [*map(int, input().split())]
	(l, r) = (0, max(a))
	while l < r:
		mid = (l + r) // 2
		if sum((j if i > mid else 0 for (i, j) in zip(a, b))) <= mid:
			r = mid
		else:
			l = mid + 1
	print(l)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	(*a,) = map(int, input().split())
	(*b,) = map(int, input().split())
	ab = [(ai, -bi) for (ai, bi) in zip(a, b)]
	ab.sort()
	tmp = 0
	for i in range(n):
		(ai, bi) = ab[-1]
		if tmp - bi <= ai:
			tmp -= bi
			ab.pop()
		else:
			break
	if ab:
		print(max(ab[-1][0], tmp))
	else:
		print(tmp)


import sys
from math import gcd, sqrt, ceil, log2
from collections import defaultdict, Counter, deque
from bisect import bisect_left, bisect_right
import math
sys.setrecursionlimit(2 * 10 ** 5 + 10)
import heapq
from itertools import permutations
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
aa = 'abcdefghijklmnopqrstuvwxyz'

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def get_sum(bit, i):
	s = 0
	i += 1
	while i > 0:
		s += bit[i]
		i -= i & -i
	return s

def update(bit, n, i, v):
	i += 1
	while i <= n:
		bit[i] += v
		i += i & -i

def modInverse(b, m):
	g = math.gcd(b, m)
	if g != 1:
		return -1
	else:
		return pow(b, m - 2, m)

def primeFactors(n):
	sa = []
	while n % 2 == 0:
		sa.append(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			sa.append(i)
			n = n // i
	if n > 2:
		sa.append(n)
	return sa

def seive(n):
	pri = [True] * (n + 1)
	p = 2
	while p * p <= n:
		if pri[p] == True:
			for i in range(p * p, n + 1, p):
				pri[i] = False
		p += 1
	return pri

def check_prim(n):
	if n < 0:
		return False
	for i in range(2, int(sqrt(n)) + 1):
		if n % i == 0:
			return False
	return True

def getZarr(string, z):
	n = len(string)
	(l, r, k) = (0, 0, 0)
	for i in range(1, n):
		if i > r:
			(l, r) = (i, i)
			while r < n and string[r - l] == string[r]:
				r += 1
			z[i] = r - l
			r -= 1
		else:
			k = i - l
			if z[k] < r - i + 1:
				z[i] = z[k]
			else:
				l = i
				while r < n and string[r - l] == string[r]:
					r += 1
				z[i] = r - l
				r -= 1

def search(text, pattern):
	concat = pattern + '$' + text
	l = len(concat)
	z = [0] * l
	getZarr(concat, z)
	ha = []
	for i in range(l):
		if z[i] == len(pattern):
			ha.append(i - len(pattern) - 1)
	return ha

def mergeIntervals(arr):
	arr.sort(key=lambda x: x[0])
	m = []
	s = -10000
	max = -100000
	for i in range(len(arr)):
		a = arr[i]
		if a[0] > max:
			if i != 0:
				m.append([s, max])
			max = a[1]
			s = a[0]
		elif a[1] >= max:
			max = a[1]
	if max != -100000 and [s, max] not in m:
		m.append([s, max])
	return m

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def sol(n):
	seti = set()
	for i in range(1, int(sqrt(n)) + 1):
		if n % i == 0:
			seti.add(n // i)
			seti.add(i)
	return seti

def lcm(a, b):
	return a * b // gcd(a, b)

def if_poss(a, b, x):
	seti = set()
	for i in range(n):
		if a[i] <= x:
			seti.add(i)
	ans = 0
	for j in range(n):
		if j not in seti:
			ans += b[j]
	if ans <= x:
		return True
	return False
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	min = 1
	max = 10 ** 14 + 10
	while min < max:
		mid = (min + max) // 2
		if if_poss(a, b, mid):
			max = mid - 1
		else:
			min = mid + 1
	if if_poss(a, b, min):
		print(min)
	else:
		print(min + 1)


T = int(input())
for _ in range(0, T):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	low = 0
	high = max(a)
	ans = max(a)
	while low <= high:
		mid = low + high >> 1
		tot = 0
		for i in range(0, len(a)):
			if a[i] > mid:
				tot += b[i]
		if tot <= mid:
			ans = min(ans, mid)
			high = mid - 1
		else:
			low = mid + 1
	print(ans)


T = int(input())
to_print = []
while T:
	T -= 1
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	if n == 1:
		to_print.append(min(a[0], b[0]))
		continue
	ab = list(zip(a, b))
	ab.sort()
	k = n - 1
	suffix_sum = 0
	while suffix_sum <= ab[k][0] and k >= 0:
		suffix_sum += ab[k][1]
		k -= 1
	to_print.append(min(ab[k + 1][0], suffix_sum))
else:
	print('\n'.join(map(str, to_print)))


from collections import deque
cases = int(input())
for t in range(cases):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ls = []
	mv = max(a)
	for i in range(n):
		ls.append((a[i], b[i]))
	ls = sorted(ls, reverse=True)
	golist = deque()
	golist.append(0)
	dellist = deque()
	dellist.appendleft(ls[-1][0])
	for i in range(n):
		golist.append(golist[-1] + ls[i][-1])
	for i in range(n - 2, -1, -1):
		dellist.appendleft(max(dellist[0], ls[i][0]))
	dellist.append(0)
	cost = []
	for i in range(n + 1):
		cost.append(max(golist[i], dellist[i]))
	print(min(cost))


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify, _heapify_max, _heappop_max

def main():
	mod = 1000000007
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	tc = ri()
	for _ in range(tc):
		n = ri()
		a = ria()
		b = ria()
		ls = []
		for i in range(n):
			ls.append((a[i], b[i]))
		ls = sorted(ls, reverse=True)
		ans = ls[0][0]
		t = 0
		for i in range(n - 1):
			t += ls[i][1]
			ans = min(ans, max(t, ls[i + 1][0]))
		ans = min(ans, t + ls[n - 1][1])
		print(ans)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


for _ in range(int(input())):
	a = int(input())
	b = list(map(int, input().split()))
	c = list(map(int, input().split()))
	k = sorted(zip(b, c))
	ans = 0
	for i in c:
		ans += i
	st = 0
	out = ans
	for i in k:
		ans -= i[1]
		if i[0] > ans:
			t = i[0]
		else:
			t = ans
		out = min(out, t)
	print(out)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	p = []
	for i in range(n):
		p.append((a[i], b[i]))
	p.sort(reverse=True)
	time = 0
	r = 0
	for (a, b) in p:
		if r + b < a:
			time = max(time, r + b)
			r = r + b
		else:
			time = max(time, a)
	print(time)


def solve(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	if sum(b) <= min(a):
		print(sum(b))
		return
	nums = [[x, y] for (x, y) in zip(a, b)]
	nums = sorted(nums, key=lambda x: -x[0])
	ans = nums[-1][0]
	su = 0
	for (x, y) in nums:
		if su + y < x:
			su += y
		else:
			ans = max(x, su)
			break
	print(ans)

def main():
	T = int(input())
	for t in range(T):
		solve(t + 1)
main()


t = int(input())
ans = []
while t:
	t -= 1
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	if n == 1:
		ans.append(min(a[0], b[0]))
		continue
	c = list(zip(a, b))
	c.sort(key=lambda x: (-x[0], x[1]))
	for i in range(1, n):
		c[i] = (c[i][0], c[i][1] + c[i - 1][1])
	ans.append(max(map(min, c)))
else:
	print('\n'.join(map(str, ans)))


from sys import stdin, stdout
import math, bisect
from collections import Counter, deque, defaultdict
L = lambda : list(map(int, stdin.readline().strip().split()))
M = lambda : map(int, stdin.readline().strip().split())
I = lambda : int(stdin.readline().strip())
S = lambda : stdin.readline().strip()
C = lambda : stdin.readline().strip().split()

def pr(a):
	print(' '.join(list(map(str, a))))

def solve():
	n = I()
	a = L()
	b = L()
	c = [(a[i], b[i]) for i in range(n)]
	c.sort()
	x = sum(b)
	ans = x
	s = 0
	for i in range(n):
		s += c[i][1]
		ans = min(ans, max(c[i][0], x - s))
	print(ans)
for _ in range(I()):
	solve()


from sys import stdin, stdout
input = stdin.readline
print = lambda x: stdout.write(str(x) + '\n')
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = [(a[i], b[i]) for i in range(n)]
	c.sort(key=lambda x: x[0], reverse=True)
	(dil, pic) = (c[0][0], 0)
	ans = dil
	for (i, j) in c:
		if max(pic, i) < ans:
			ans = max(pic, i)
		pic += j
	if pic < ans:
		ans = pic
	print(ans)


import sys
for _ in range(int(sys.stdin.readline())):
	n = int(sys.stdin.readline().strip())
	a = list(map(int, sys.stdin.readline().strip().split(' ')))
	b = list(map(int, sys.stdin.readline().strip().split(' ')))
	c = []
	for i in range(n):
		c.append((a[i], b[i]))
	c.sort()
	m = c[-1][0]
	d = 0
	for i in range(len(c) - 2, -1, -1):
		if max(c[i][0], d + c[i + 1][1]) <= m:
			d += c[i + 1][1]
			m = c[i][0]
		else:
			break
	else:
		if d < m:
			d += c[0][1]
			print(min(d, m))
			continue
	print(max(d, m))


t = int(input())
for case in range(t):
	n = int(input())
	a = [int(x) for x in input().split(' ')]
	b = [int(x) for x in input().split(' ')]
	a = [(-1, 0)] + list(enumerate(a))
	b = {i: x for (i, x) in enumerate(b)}
	a.sort(key=lambda x: x[1])
	p = 0
	while len(a) > 1 and p + b[a[-1][0]] <= a[-1][1]:
		x = a.pop()
		p += b[x[0]]
	print(max(p, a[-1][1]))


t = int(input())
for _ in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	n = len(A)

	def solve():
		sumb = sum(B)
		mina = min(A)
		maxa = max(A)
		elems = list(zip(A, B))
		elems.sort(key=lambda tup: -tup[0])
		delivery = maxa
		pickup = 0
		result = max(delivery, pickup)
		for i in range(n):
			(a, b) = elems[i]
			if i == n - 1:
				delivery = 0
				pickup += b
			else:
				delivery = abs(elems[i + 1][0])
				pickup += b
			currTime = max(delivery, pickup)
			result = min(result, currTime)
		return result
	result = solve()
	print(result)


import sys
import math

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def MI():
	return list(map(int, sys.stdin.readline().split()))

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	n = II()
	a = LI()
	b = LI()
	b = sorted(enumerate(b), key=lambda x: a[x[0]])
	b = [i[1] for i in b]
	a.sort()
	x = []
	s = 0
	for i in range(n - 1, -1, -1):
		s += b[i]
		x.append(s)
	x = x[:][::-1]
	ans = s
	for i in range(n):
		if i == n - 1:
			ans = min(ans, a[i])
		else:
			ans = min(ans, max(a[i], x[i + 1]))
	print(ans)


def solve(x, l1, l2):
	l = [(l1[t], l2[t]) for t in range(x)]
	l.sort(reverse=1)
	l.append((0, 0))
	s = 0
	for t in range(x):
		s = s + l[t][1]
		if s >= l[t + 1][0]:
			return min(s, l[t][0])
			break
	else:
		return s
la = []
lb = []
lc = []
ans = []
suffer_time = int(input())
for t in range(suffer_time):
	la.append(int(input()))
	lb.append(list(map(int, input().split())))
	lc.append(list(map(int, input().split())))
for t in range(suffer_time):
	ans.append(solve(la[t], lb[t], lc[t]))
for i in ans:
	print(i)


ans = []
for i in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	dishes = sorted(list(zip(a, b)), reverse=True)
	out = 0
	for dish in dishes:
		out += dish[1]
		if out >= dish[0]:
			out = max(dish[0], out - dish[1])
			break
	ans.append(out)
print('\n'.join(map(str, ans)))


import sys
input = sys.stdin.readline
from collections import defaultdict as dc
from collections import Counter
from bisect import bisect_right, bisect_left
import math
from heapq import heapify, heappop, heappush
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = []
	for i in range(n):
		l.append([a[i], b[i]])
	l.sort(key=lambda x: (x[0], x[1]))
	p = [0] * n
	p[0] = l[0][0]
	for i in range(1, n):
		p[i] = max(p[i - 1], l[i][0])
	q = [0] * n
	q[-1] = l[-1][1]
	for i in range(n - 2, -1, -1):
		q[i] = l[i][1] + q[i + 1]
	m = sys.maxsize
	for i in range(n + 1):
		if i == 0:
			m = min(m, q[0])
		elif i == n:
			m = min(m, p[-1])
		else:
			m = min(m, max(p[i - 1], q[i]))
	print(m)


for _ in range(int(input())):
	n = int(input())
	a = [*list(map(int, input().split()))]
	b = [*list(map(int, input().split()))]
	lo = 0
	hi = sum(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if sum((y if x > mid else 0 for (x, y) in zip(a, b))) <= mid:
			hi = mid
		else:
			lo = mid + 1
	print(lo)


t = int(input())
for i in range(t):
	n = int(input())
	b = list(map(int, input().split()))
	c = list(map(int, input().split()))
	k = sorted(zip(b, c))
	ans = sum(c)
	out = ans
	for i in k:
		ans -= i[1]
		out = min(out, max(i[0], ans))
	print(out)


t = int(input())
output = []
for i in range(t):
	n = int(input())
	a = [int(j) for j in input().split()]
	b = [int(j) for j in input().split()]
	c = sorted(list(zip(a, b)), reverse=True)
	time = 0
	for k in c:
		time += k[1]
		if time >= k[0]:
			time = max(k[0], time - k[1])
			break
	output.append(time)
print('\n'.join(map(str, output)))


from itertools import accumulate
from math import inf
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
T = int(input())
for _ in range(T):
	n = int(input())
	courier = list(map(int, input().split()))
	self_ = list(map(int, input().split()))
	arr = [(a, b) for (a, b) in zip(courier, self_)]
	arr.sort()
	cum = list(accumulate([x[1] for x in arr]))
	ans = min(cum[-1], arr[-1][0])
	for i in range(n):
		ans = min(ans, max(arr[i][0], cum[-1] - cum[i]))
	print(ans)


import io, os, sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	n = int(input())
	l1 = list(map(int, input().split()))
	l2 = list(map(int, input().split()))
	tt = [] + [(l1[i], l2[i]) for i in range(n)]
	tt.sort()
	px = -1
	old = tt[-1][0]
	rp = 0
	flag = True
	while px >= -n + 1:
		k = tt[px][1]
		t = max(tt[px - 1][0], rp + k)
		if t <= old:
			rp += k
			px -= 1
			old = t
		else:
			flag = False
			sys.stdout.write(str(old) + '\n')
			break
	if flag:
		sys.stdout.write(str(min(old, rp + tt[0][1])) + '\n')


import sys, os, io
I = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for tc in range(1, 1 + int(I())):
	n = int(I())
	a = list(map(int, I().split()))
	b = list(map(int, I().split()))
	d = dict()
	for i in range(n):
		if a[i] not in d.keys():
			d[a[i]] = b[i]
		else:
			d[a[i]] += b[i]
	(ans, sm) = (int(9000000000000.0), 0)
	for k in sorted(d.keys())[::-1]:
		ans = min(ans, max(k, sm))
		sm += d[k]
	print(min(ans, sm))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	tup = [[0, 0]] + sorted([[a[i], b[i]] for i in range(n)], key=lambda x: x[0])
	tup += [[0, 0]]
	for i in range(n - 1, -1, -1):
		tup[i][1] += tup[i + 1][1]
	res = max(tup[0][0], tup[1][1])
	for i in range(1, n + 1):
		res = min(res, max(tup[i][0], tup[i + 1][1]))
	print(res)


import sys
import math
import collections
import bisect

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_string():
	return sys.stdin.readline().strip()
for t in range(int(input())):
	n = int(input())
	a = get_list()
	b = get_list()
	case1 = sum(a)
	case2 = sum(b)
	case3 = case2
	maxim = 0
	ans = 10 ** 10
	arr = []
	for i in range(n):
		val = [a[i], b[i]]
		arr.append(val)
	arr.sort()
	for i in range(n):
		val = max(case3 - arr[i][1], arr[i][0])
		case3 -= arr[i][1]
		ans = min(ans, val)
	print(min(case2, case1, ans))


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	pick = 0
	delivery = 0
	l = []
	for i in range(n):
		l.append([a[i], b[i]])
	l.sort(reverse=True)
	a = []
	b = []
	for i in range(n):
		a.append(l[i][0])
		b.append(l[i][1])
	for i in range(n):
		if pick + b[i] < a[i]:
			pick = pick + b[i]
		else:
			delivery = max(delivery, a[i])
	print(max(pick, delivery))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ab = [(a[i], b[i]) for i in range(n)]
	ab.sort(key=lambda x: x[0], reverse=True)
	ruiseki = [0] * n
	for i in range(1, n):
		ruiseki[i] = ruiseki[i - 1] + ab[i - 1][1]
	ans = sum(b)
	for i in range(n):
		x = max(ruiseki[i], ab[i][0])
		ans = min(ans, x)
	print(ans)


import sys
input = sys.stdin.readline
a = int(input())
for i in range(a):
	b = int(input())
	c = input().split()
	d = input().split()
	for j in range(b):
		c[j] = [int(c[j]), int(d[j])]
	c.sort(reverse=True)
	d = c[0][0]
	e = 0
	for (j, k) in c:
		d = min(d, max(j, e))
		e += k
	d = min(d, e)
	print(d)


ans = []
for i in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	if n == 1:
		ans.append(min(a[0], b[0]))
	else:
		t = sorted(list(zip(a, b)), reverse=True)
		d_t = 0
		mi = t[0][0]
		for i in range(n):
			if t[i][0] <= t[i][1] + d_t:
				mi = max(t[i][0], d_t)
				break
			else:
				d_t += t[i][1]
		ans.append(min(mi, sum(b)))
print('\n'.join(map(str, ans)))


for _ in range(int(input())):
	n = int(input())
	l1 = list(map(int, input().split()))
	l2 = list(map(int, input().split()))
	pair = []
	for i in range(n):
		pair.append([l1[i], l2[i]])
	pair.sort()
	su = 0
	sums = []
	for i in range(n - 1, -1, -1):
		su += pair[i][1]
		sums.append(su)
	sums = sums[::-1]
	ans = pair[-1][0]
	maxi = 0
	for i in range(n):
		ans = min(ans, max(maxi, sums[i]))
		maxi = pair[i][0]
	print(ans)


n = int(input())
p = []
for i in range(n):
	m = int(input())
	a = [[0, 0] for i in range(m)]
	s = [int(x) for x in input().split()]
	n = [int(x) for x in input().split()]
	for i in range(m):
		a[i][0] = s[i]
		a[i][1] = n[i]
	a.sort(key=lambda x: x[0], reverse=True)
	t = 0
	i = 0
	while i <= m - 1 and t < a[i][0]:
		t += a[i][1]
		i += 1
	p += [str(min(t, a[i - 1][0]))]
print('\n'.join(p))


T = int(input())
for t in range(T):
	n = int(input())
	A = [int(x) for x in input().split()]
	B = [int(x) for x in input().split()]
	max_wait = 0
	driving_time = 0
	nA = []
	nB = []
	both = []
	for i in range(n):
		if B[i] >= A[i]:
			max_wait = max(max_wait, A[i])
		else:
			nA.append(A[i])
			nB.append(B[i])
			both.append((A[i], B[i]))
	both.sort(key=lambda tup: tup[0], reverse=True)
	for tup in both:
		if tup[0] <= max_wait:
			del tup
			continue
		if driving_time + tup[1] < max(max_wait, tup[0]):
			driving_time += tup[1]
		else:
			max_wait = max(max_wait, tup[0])
	print(max(max_wait, driving_time))


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = 0
	r = max(a)
	while l < r:
		m = l + r >> 1
		s = 0
		for i in range(n):
			s += b[i] if a[i] > m else 0
		if s > m:
			l = m + 1
		else:
			r = m
	print(l)


import sys
import time
import os
from math import sqrt, log, log2, log10, gcd, floor, pow, sin, cos, tan, pi, inf, factorial
from copy import copy, deepcopy
from sys import exit, stdin, stdout
from collections import Counter, defaultdict, deque
from itertools import permutations
import heapq
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
mod = 1000000007
iinp = lambda : int(sys.stdin.readline())
inp = lambda : sys.stdin.readline().strip()
strl = lambda : list(inp().strip().split(' '))
intl = lambda : list(map(int, inp().split(' ')))
mint = lambda : map(int, inp().split())
flol = lambda : list(map(float, inp().split(' ')))
flush = lambda : stdout.flush()

def permute(nums):

	def fun(arr, nums, cur, v):
		if len(cur) == len(nums):
			arr.append(cur.copy())
		i = 0
		while i < len(nums):
			if v[i]:
				i += 1
				continue
			else:
				cur.append(nums[i])
				v[i] = 1
				fun(arr, nums, cur, v)
				cur.pop()
				v[i] = 0
				i += 1
		return arr
	res = []
	nums.sort()
	v = [0] * len(nums)
	return fun(res, nums, [], v)

def subsets(res, index, arr, cur):
	res.append(cur.copy())
	for i in range(index, len(arr)):
		cur.append(arr[i])
		subsets(res, i + 1, arr, cur)
		cur.pop()
	return res

def sieve(N):
	root = int(sqrt(N))
	primes = [1] * (N + 1)
	(primes[0], primes[1]) = (0, 0)
	for i in range(2, root + 1):
		if primes[i]:
			for j in range(i * i, N + 1, i):
				primes[j] = 0
	return primes

def bs(arr, l, r, x):
	if x < arr[0] or x > arr[len(arr) - 1]:
		return -1
	while l <= r:
		mid = l + (r - l) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	p = int(sqrt(n))
	for i in range(5, p + 1, 6):
		if n % i == 0 or n % (i + 2) == 0:
			return False
	return True

def solve():
	n = iinp()
	a = intl()
	b = intl()
	ans = 0
	arr = []
	for i in range(n):
		arr.append([a[i], b[i]])
	arr.sort()
	s = 0
	for i in range(n - 1, -1, -1):
		s += arr[i][1]
		if s < arr[i][0]:
			continue
		elif s > arr[i][0]:
			ans = max(s - arr[i][1], arr[i][0])
			break
		else:
			ans = arr[i][0]
	if ans == 0:
		print(sum(b))
	else:
		print(ans)
start_time = time.time()
for _ in range(iinp()):
	solve()


import sys, threading, os.path
import string, heapq
sys.setrecursionlimit(10 ** 6)
threading.stack_size(2 ** 27)

def main():
	if os.path.exists('in.rtf'):
		input = open('in.rtf', 'r')
	else:
		input = sys.stdin
	t = int(input.readline())
	results = []
	for i in range(t):
		n = int(input.readline())
		ai = list(map(int, input.readline().split()))
		bi = list(map(int, input.readline().split()))
		(sum_a, sum_b) = (0, 0)
		h = []
		result = 0
		for j in range(n):
			heapq.heappush(h, (-ai[j], j))
		result = min(ai[0], bi[0])
		while len(h) > 0:
			temp = heapq.heappop(h)
			sum_a = -temp[0]
			sum_b += bi[temp[1]]
			result = max(result, min(sum_a, sum_b))
		results.append(result)
	output = '\n'.join(map(str, results))
	if os.path.exists('out.rtf'):
		open('out.rtf', 'w').writelines(str(output))
	else:
		sys.stdout.write(str(output))
main()


t = []
for _ in range(int(input())):
	d = int(input())
	cou = [*map(int, input().split())]
	own = [*map(int, input().split())]
	com = sorted(zip(cou, own), reverse=True)
	time = 0
	for k in com:
		time += k[1]
		if time >= k[0]:
			time = max(k[0], time - k[1])
			break
	t.append(time)
print('\n'.join(map(str, t)))


from math import gcd
from collections import defaultdict as dd
import sys
input = sys.stdin.readline
t = int(input())
while t:
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = [(a[i], b[i]) for i in range(n)]
	l.sort(reverse=True)
	su = 0
	lol = 0
	for i in range(n):
		(at, bt) = l[i]
		if su + bt <= at:
			su += bt
		else:
			lol = 1
			break
	if lol == 0:
		print(su)
	else:
		print(max(su, at))
	t -= 1


for _ in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	b = [*map(int, input().split())]
	d = []
	for i in range(n):
		d.append([a[i], b[i]])
	d = sorted(d)
	suff = [d[-1][1]]
	for i in range(n - 2, -1, -1):
		suff.append(d[i][1] + suff[n - i - 2])
	i = 0
	suff = suff[::-1]
	while i < n and d[i][0] <= suff[i]:
		i += 1
	if d[i - 1][0] > suff[0]:
		print(suff[0])
	elif i == n:
		print(d[i - 1][0])
	else:
		print(max(d[i - 1][0], suff[i]))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def prod(a, mod=10 ** 9 + 7):
	ans = 1
	for each in a:
		ans = ans * each % mod
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	(alpha, omega) = (0, 10 ** 24)
	while alpha < omega:
		mid = (alpha + omega) // 2
		walk = 0
		for i in range(n):
			if a[i] <= mid:
				continue
			else:
				walk += b[i]
		if walk <= mid:
			omega = mid
		else:
			alpha = mid + 1
	print(omega)


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		ab = []
		for i in range(n):
			ab.append((a[i], b[i]))
		ab.sort(reverse=True)
		walking_time = z = 0
		for j in range(n):
			el = ab[j]
			if walking_time + el[1] < el[0]:
				walking_time += el[1]
				z += 1
			else:
				break
		if z == n:
			courier_time = walking_time
		else:
			courier_time = ab[z][0]
		print(max(walking_time, courier_time))
main()


def read_ints():
	return map(int, input().split())
t_n = int(input())
for i_t in range(t_n):
	n = int(input())
	ab_pairs = zip(read_ints(), read_ints())
	ab_pairs = sorted(ab_pairs, key=lambda ab: ab[0])
	current_b_sum = sum((ab[1] for ab in ab_pairs))
	current_a_max = 0
	result = max(current_b_sum, current_a_max)
	for (a, b) in ab_pairs:
		current_b_sum -= b
		current_a_max = a
		potential_result = max(current_b_sum, current_a_max)
		if potential_result < result:
			result = potential_result
	print(result)


import sys
input = sys.stdin.readline
cases = int(input())
for i in range(cases):
	numberofres = int(input())
	diliver = list(map(int, input().split()))
	run = list(map(int, input().split()))
	data = []
	for i in range(len(diliver)):
		data.append([diliver[i], run[i]])
	data.sort(key=lambda x: x[0])
	currenttime = 0
	while True:
		stat = False
		if data[-1][0] > currenttime + data[-1][1]:
			currenttime += data[-1][1]
			data.pop()
			stat = True
		if stat == False:
			break
		if len(data) == 0:
			break
	if len(data) == 0:
		sys.stdout.write(str(currenttime) + '\n')
	else:
		sys.stdout.write(str(max(currenttime, data[-1][0])) + '\n')


import sys
import math as m
mod = 1000000000.0 + 7

def fi():
	return sys.stdin.readline()
for _ in range(int(fi())):
	n = int(fi())
	a = list(map(int, fi().split()))
	b = list(map(int, fi().split()))
	s = []
	for i in range(n):
		s.append([a[i], b[i]])
	s.sort()
	p = 0
	ans = sys.maxsize
	for i in range(n - 1, -1, -1):
		ans = min(ans, max(p, s[i][0]))
		p += s[i][1]
	print(min(ans, p))


def check(M):
	sm = 0
	for i in range(n):
		if a[i] > M:
			sm += b[i]
	return sm <= M
gans = []
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	L = 0
	R = max(a)
	while R - L > 1:
		M = (L + R) // 2
		if check(M):
			R = M
		else:
			L = M
	gans.append(R)
print(*gans, sep='\n')


t = int(input())
ans = []
for i in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	(a, b) = zip(*sorted(zip(a, b)))
	c1 = a[n - 1]
	c2 = 0
	time = [a[n - 1]]
	while c1 > c2 and n - 2 >= 0:
		c1 = a[n - 2]
		c2 += b[n - 1]
		time.append(max(c1, c2))
		n = n - 1
	time.append(sum(b))
	ans.append(min(time))
for g in ans:
	print(g)


import sys

def input():
	return sys.stdin.readline()

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))

	def ispossible(x):
		res = 0
		for i in range(n):
			if a[i] > x:
				res += b[i]
		return res <= x
	l = 0
	r = 10 ** 9
	while r - l > 1:
		m = (r + l) // 2
		if ispossible(m):
			r = m
		else:
			l = m
	print(r)
	return

def main():
	t = int(input())
	for i in range(t):
		solve()
	return
main()


import sys
t = int(input())
for test in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	b = list(map(int, input().split(' ')))
	ab = zip(a, b)
	asort = [y for (y, _) in sorted(zip(a, b))]
	bsort = [x for (_, x) in sorted(zip(a, b))]
	bsum = 0
	finito = False
	for i in reversed(range(n)):
		if bsum + bsort[i] > asort[i]:
			res = max(asort[i], bsum)
			finito = True
			break
		else:
			bsum += bsort[i]
	if not finito:
		res = bsum
	print(res)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	b = [*map(int, input().split())]
	L = 0
	R = max(a)
	while L < R:
		mid = (L + R) // 2
		if sum((y if x > mid else 0 for (x, y) in zip(a, b))) <= mid:
			R = mid
		else:
			L = mid + 1
	print(L)


for _ in range(int(input())):
	n = int(input())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	a = []
	for i in range(n):
		a.append((x[i], y[i]))
	a.sort(key=lambda x: x[0])
	a.reverse()
	delivered = 0
	travelled = 0
	for i in range(n):
		if a[i][0] > travelled + a[i][1]:
			travelled += a[i][1]
		else:
			delivered = a[i][0]
			break
	print(max(delivered, travelled))


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
cases = int(input())
for t in range(cases):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ls = []
	mv = max(a)
	for i in range(n):
		ls.append((a[i], b[i]))
	ls = sorted(ls, reverse=True)
	golist = deque()
	golist.append(0)
	dellist = deque()
	dellist.appendleft(ls[-1][0])
	for i in range(n):
		golist.append(golist[-1] + ls[i][-1])
	for i in range(n - 2, -1, -1):
		dellist.appendleft(max(dellist[0], ls[i][0]))
	dellist.append(0)
	cost = []
	for i in range(n + 1):
		cost.append(max(golist[i], dellist[i]))
	print(min(cost))


import math
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(n):
		a[i] = (a[i], b[i])
	a.sort(key=lambda x: x[0])
	curr = 0
	if a[n - 1][0] <= a[n - 1][1]:
		print(a[n - 1][0])
		continue
	curr = a[n - 1][1]
	i = n - 2
	ans = -1
	while i >= 0 and curr <= a[i][0]:
		curr += a[i][1]
		if curr > a[i][0]:
			curr -= a[i][0]
			ans = a[i][0]
			break
		i -= 1
	if ans > 0:
		print(ans)
	else:
		print(curr)


def xxx(x):
	global a, b
	res = 0
	for i in range(len(a)):
		if a[i] > x:
			res += b[i]
	if res <= x:
		return True
	else:
		return False
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	i1 = 0
	i2 = sum(b)
	while i2 - i1 > 1:
		m = (i1 + i2) // 2
		if xxx(m):
			i2 = m
		else:
			i1 = m
	print(i2)


import sys
t = int(sys.stdin.readline())
for _ in range(t):
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	b = list(map(int, sys.stdin.readline().split()))
	tmp = list(zip(a, b))
	tmp.sort(reverse=True)
	buy = 0
	for (i, j) in tmp:
		buy += j
		if buy > i:
			buy = max(buy - j, i)
			break
	print(buy)


t = int(input())
for _ in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))

	def is_ok(x):
		t = 0
		for (a, b) in zip(A, B):
			if a > x:
				t += b
		if t <= x:
			return True
		else:
			return False
	ng = 0
	ok = 10 ** 18
	while ng + 1 < ok:
		c = (ng + ok) // 2
		if is_ok(c):
			ok = c
		else:
			ng = c
	print(ok)


for _ in range(int(input())):
	n = int(input())
	output = 0
	first = list(map(int, input().split()))
	second = list(map(int, input().split()))
	temp = []
	for i in range(n):
		temp.append([first[i], second[i]])
	temp.sort(key=lambda x: x[0])
	temp.reverse()
	for i in range(n):
		if output <= temp[i][0]:
			output += temp[i][1]
		else:
			break
		if output >= temp[i][0]:
			output = temp[i][0]
			break
	print(output)


import math
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	l = []
	n = len(a)
	for i in range(n):
		l.append([a[i], b[i]])
	l.sort(reverse=True)
	ans = [max(a), sum(b)]
	s = 0
	for i in range(n - 1):
		s += l[i][1]
		ans.append(max(s, l[i + 1][0]))
	print(min(ans))


import sys

def partition(arr, low, high):
	i = low - 1
	pivot = arr[high]
	for j in range(low, high):
		if arr[j] <= pivot:
			i = i + 1
			(arr[i], arr[j]) = (arr[j], arr[i])
			(brr[i], brr[j]) = (brr[j], brr[i])
	(arr[i + 1], arr[high]) = (arr[high], arr[i + 1])
	(brr[i + 1], brr[high]) = (brr[high], brr[i + 1])
	return i + 1

def quickSort(arr, low, high):
	if len(arr) == 1:
		return arr
	if low < high:
		pi = partition(arr, low, high)
		quickSort(arr, low, pi - 1)
		quickSort(arr, pi + 1, high)
a = int(input())
for i in range(a):
	b = int(input())
	arr = list(map(int, sys.stdin.readline().split()))
	brr = list(map(int, sys.stdin.readline().split()))
	d = dict()
	for i in range(0, len(arr)):
		d[arr[i]] = set()
	for i in range(0, len(arr)):
		d[arr[i]].add(i)
	arr.sort()
	nbrr = []
	for i in arr:
		nbrr.append(brr[d[i].pop()])
	brr = nbrr
	ans = float('inf')
	minn = -float('inf')
	sbrr = [0]
	for i in range(0, len(brr)):
		sbrr.append(sbrr[len(sbrr) - 1] + brr[i])
	for i in range(0, len(arr)):
		minn = max(arr[i], minn)
		ans = min(ans, max(minn, sbrr[len(sbrr) - 1] - sbrr[i + 1]))
	s = sum(brr)
	print(min(s, ans))


import math
import time
n = int(input())
ans = []
for i in range(n):
	m = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = sorted(list(zip(a, b)), reverse=True)
	d = 0
	if m == 1:
		ans.append(min(c[0][0], c[0][1]))
	else:
		for j in range(m - 1):
			d += c[j][1]
			if d > c[j + 1][0]:
				ans.append(min(c[j][0], d))
				break
			if j == m - 2:
				ans.append(min(c[j + 1][0], d + c[j + 1][1]))
				break
for i in ans:
	print(i)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	worst = [(a[i], b[i]) for i in range(n)]
	worst.sort(reverse=True)
	time = 0
	for (x, y) in worst:
		if x - time <= y:
			time = max(x, time)
			break
		else:
			time += y
	print(time)


import collections
import math
import collections
import sys
from functools import reduce
import decimal
sys.setrecursionlimit(10 ** 9)
decimal.getcontext().rounding = decimal.ROUND_HALF_UP
graphDict = collections.defaultdict
queue = collections.deque

class Graphs:

	def __init__(self):
		self.graph = graphDict(list)

	def add_edge(self, u, v):
		self.graph[u].append(v)

	def dfs_utility(self, nodes, visited_nodes):
		visited_nodes.add(nodes)
		for neighbour in self.graph[nodes]:
			if neighbour not in visited_nodes:
				self.dfs_utility(neighbour, visited_nodes)
			else:
				return neighbour

	def dfs(self, node):
		Visited = set()
		self.dfs_utility(node, Visited)

	def bfs(self, node):
		visited = set()
		if node not in visited:
			queue.append(node)
			visited.add(node)
		while queue:
			parent = queue.popleft()
			print(parent)
			for item in self.graph[parent]:
				if item not in visited:
					queue.append(item)
					visited.add(item)

def rounding(n):
	return int(decimal.Decimal(f'{n}').to_integral_value())

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def inp():
	return sys.stdin.readline().strip()

def map_inp(v_type):
	return map(v_type, inp().split())

def list_inp(v_type):
	return list(map_inp(v_type))
for _ in range(int(inp())):
	n = int(inp())
	a = list_inp(int)
	b = list_inp(int)
	dic = []
	index = 1
	for (i, j) in zip(a, b):
		dic.append([i, j])
	dic.sort(reverse=True)
	temp = 0
	ans = 0
	for i in dic:
		if temp + i[1] < i[0]:
			temp += i[1]
		else:
			ans = max(i[0], ans)
	print(max(temp, ans))


for _ in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	b = [*map(int, input().split())]
	L = 0
	R = max(a)
	while L < R:
		mid = (L + R) // 2
		if sum((y if x > mid else 0 for (x, y) in zip(a, b))) <= mid:
			R = mid
		else:
			L = mid + 1
	print(L)


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	both = []
	for i in range(n):
		both.append([a[i], b[i]])
	both.sort()
	a = [i[0] for i in both]
	b = [i[1] for i in both]
	Suffix = b.copy()
	for i in range(-2, -n - 1, -1):
		Suffix[i] = Suffix[i] + Suffix[i + 1]
	ans = 10000000000000
	for i in range(n - 1):
		ans = min(ans, max(a[i], Suffix[i + 1]))
	ans = min(ans, a[n - 1], Suffix[0])
	print(ans)


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
from operator import add, mul, sub, xor, truediv, floordiv
from functools import *
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa = ifa[::-1]

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def linc(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t > f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rinc(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t < f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def ldec(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t < f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rdec(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t > f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def binfun(x):
	c = 0
	for w in arr:
		c += ceil(w / x)
	return c

def lowbit(n):
	return n & -n

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class smt:

	def __init__(self, l, r, arr):
		self.l = l
		self.r = r
		self.value = (1 << 31) - 1 if l < r else arr[l]
		mid = (l + r) // 2
		if l < r:
			self.left = smt(l, mid, arr)
			self.right = smt(mid + 1, r, arr)
			self.value &= self.left.value & self.right.value

	def setvalue(self, x, val):
		if self.l == self.r:
			self.value = val
			return
		mid = (self.l + self.r) // 2
		if x <= mid:
			self.left.setvalue(x, val)
		else:
			self.right.setvalue(x, val)
		self.value = self.left.value & self.right.value

	def ask(self, l, r):
		if l <= self.l and r >= self.r:
			return self.value
		val = (1 << 31) - 1
		mid = (self.l + self.r) // 2
		if l <= mid:
			val &= self.left.ask(l, r)
		if r > mid:
			val &= self.right.ask(l, r)
		return val

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] < self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return prime

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		for v in graph[u]:
			if v not in d or d[v] > d[u] + graph[u][v]:
				d[v] = d[u] + graph[u][v]
				heappush(heap, (d[v], v))
	return d

def GP(it):
	res = []
	for (ch, g) in groupby(it):
		res.append((ch, len(list(g))))
	return res
t = N()
for i in range(t):
	n = N()
	a = RLL()
	b = RLL()
	cur = 0
	res = sorted([(a[i], b[i]) for i in range(n)], reverse=True)
	ans = res[0][0]
	i = 0
	while cur < ans:
		cur += res[i][1]
		if i < n - 1:
			ans = min(ans, max(res[i + 1][0], cur))
		else:
			ans = min(ans, cur)
		i += 1
	print(ans)


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, A, B):

	def isPossible(thres):
		total = 0
		for (a, b) in zip(A, B):
			if a > thres:
				total += b
		return total <= thres
	best = float('inf')
	lo = 0
	hi = max(max(A), max(B), sum(A), sum(B)) + 1
	while lo <= hi:
		mid = (lo + hi) // 2
		if isPossible(mid):
			best = min(best, mid)
			hi = mid - 1
		else:
			lo = mid + 1
	return best
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
	(N,) = [int(x) for x in input().split()]
	A = [int(x) for x in input().split()]
	B = [int(x) for x in input().split()]
	ans = solve(N, A, B)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	p = []
	an = 10000000001
	s = 0
	for i in range(n):
		s += b[i]
		p.append([a[i], b[i]])
	s1 = s
	p.sort()
	for i in range(n):
		s -= p[i][1]
		an = min(an, max(p[i][0], s))
	print(min(an, s1))


for _ in range(int(input())):
	n = int(input())
	a = [int(num) for num in input().split(' ')]
	b = [int(num) for num in input().split(' ')]
	arr = []
	for i in range(n):
		arr.append([a[i], b[i]])
	arr.sort(key=lambda x: x[0], reverse=True)
	time = arr[0][0]
	x = 0
	for i in range(n):
		if x + arr[i][1] < arr[i][0]:
			x = x + arr[i][1]
		else:
			x = max(x, arr[i][0])
			break
	print(x)


T = int(input())
for _ in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = []
	for i in range(n):
		l.append([a[i], b[i]])
	l.sort(key=lambda x: x[0], reverse=True)
	pick = 0
	time = 0
	for i in l:
		if i[0] <= pick + i[1]:
			time = max(time, i[0])
		else:
			pick += i[1]
			time = max(time, pick)
	print(time)


m = int(input())
print0 = [0] * m
for i in range(m):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = list(zip(a, b))
	c = sorted(c, key=lambda x: x[0], reverse=1)
	d = 0
	if n == 1:
		print0[i] = str(min(c[0][0], c[0][1]))
	else:
		for j in range(n - 1):
			d += c[j][1]
			if d > c[j + 1][0]:
				print0[i] = str(min(c[j][0], d))
				break
			if j == n - 2:
				print0[i] = str(min(c[j + 1][0], d + c[j + 1][1]))
				break
print('\n'.join(print0))


import sys, math
mod = 10 ** 9 + 7
md = 998244353
input = lambda : sys.stdin.readline().strip()
inp = lambda : list(map(int, input().split()))
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = [[i, j] for (i, j) in zip(a, b)]
	c = sorted(c, key=lambda x: (-x[0], x[1]))
	ans = max(a)
	f = 0
	final = c[0][0]
	for i in range(n):
		if f + c[i][1] <= c[i][0]:
			f += c[i][1]
		else:
			final = max(c[i][0], f)
			break
		prev = c[i][0]
	else:
		final = f
	print(final)


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = []
	for i in range(len(a)):
		c.append([a[i], b[i]])
	c.sort()
	x = sum(b)
	m = 10 ** 18
	for i in range(len(c)):
		m = min(m, max(c[i][0], x - c[i][1]))
		x -= c[i][1]
	print(min(m, sum(b), max(a)))


from collections import Counter
import math
import sys
import heapq
from bisect import bisect, bisect_left, bisect_right

def input():
	return sys.stdin.readline().strip()

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def mod():
	return 10 ** 9 + 7
for i in range(INT()):
	n = INT()
	a = LIST()
	b = LIST()
	index = [[0, 0] for i in range(n)]
	for i in range(n):
		index[i] = [a[i], b[i]]
	index.sort()
	ans = 10 ** 10
	check = 0
	for i in range(n - 1, -1, -1):
		ans = min(ans, index[i][0] + max(0, check - index[i][0]))
		check += index[i][1]
	print(min(ans, check))


T = int(input())
for _ in range(T):
	n = int(input())
	data = [[0] * n for _ in range(2)]
	data[0] = list(map(int, input().split()))
	data[1] = list(map(int, input().split()))
	graph = list()
	for i in range(n):
		graph.append([data[0][i], data[1][i]])
	graph.sort(key=lambda x: (x[0], x[1]), reverse=True)
	prevmintime = graph[0][0]
	prevwalktime = 0
	for i in range(n):
		if i != n - 1:
			mintime = graph[i + 1][0]
		else:
			mintime = 0
		walktime = prevwalktime + graph[i][1]
		if max(prevmintime, prevwalktime) >= max(mintime, walktime):
			prevwalktime = walktime
			prevmintime = mintime
		else:
			break
	print(max(prevmintime, prevwalktime))


import sys
input = iter(sys.stdin.read().splitlines()).__next__
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	times = list(zip(a, b))
	times.sort()
	pickup_time = sum(b)
	best_time = pickup_time
	for num_deliveries in range(1, n + 1):
		pickup_time -= times[num_deliveries - 1][1]
		delivery_time = times[num_deliveries - 1][0]
		best_time = min(best_time, max(pickup_time, delivery_time))
		if pickup_time < delivery_time:
			break
	print(best_time)


import sys
n = int(input())
ans = []
for i in range(n):
	t = int(sys.stdin.readline())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	c = sorted(list(zip(a, b)), reverse=True)
	d = 0
	for i in range(t):
		d += c[i][1]
		if d >= c[i][0]:
			d = max(c[i][0], d - c[i][1])
			break
	ans.append(d)
print('\n'.join(map(str, ans)))


Outp = []
for i in range(int(input())):
	n = int(input())
	TList = [[x, 0] for x in map(int, input().split())]
	BList = input().split()
	for j in range(n):
		TList[j][1] = int(BList[j])
	TList.sort()
	S = 0
	for k in range(n - 1, -1, -1):
		if k == 0 or S + TList[k][1] > TList[k - 1][0]:
			Outp.append(min(TList[k][0], S + TList[k][1]))
			break
		else:
			S += TList[k][1]
print('\n'.join((str(x) for x in Outp)))


import os
import sys
from io import BytesIO, IOBase
from sys import stdout, stdin
from collections import defaultdict, deque
import math

def main():
	t = int(stdin.readline())
	for _ in range(t):
		n = int(stdin.readline())
		l = list(map(int, stdin.readline().split()))
		ll = list(map(int, stdin.readline().split()))
		d = []
		for i in range(n):
			d.append([l[i], ll[i]])
		d.sort(reverse=True)
		ans = 0
		z = 0
		for i in range(n):
			if d[i][0] > z + d[i][1]:
				ans = max(ans, z + d[i][1])
				z += d[i][1]
			else:
				ans = max(ans, d[i][0])
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import os
import sys
from io import BytesIO, IOBase
import math
from itertools import permutations
from decimal import Decimal, getcontext
getcontext().prec = 25
MOD = pow(10, 9) + 7
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	l1 = list(map(int, input().split(' ')))
	l2 = list(map(int, input().split(' ')))
	l = [[0, 0] for i in range(n)]
	for i in range(n):
		l[i] = [l1[i], l2[i]]
	l.sort(reverse=True)
	if n == 1:
		print(min(l[0]))
	else:
		ans = 0
		a = l[0][0]
		b = l[0][1]
		for i in range(1, n):
			if b >= l[i][0]:
				ans = min(a, max(b, l[i][0]))
				break
			b += l[i][1]
			a = l[i][0]
		if not ans:
			ans = min(a, b)
		print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	(a, b) = ([*map(int, input().split())], [*map(int, input().split())])
	c = [(a[i], b[i]) for i in range(n)]
	c.sort()
	ans = sum(b)
	i = n - 1
	s = 0
	while i >= 0:
		ans = min(ans, max(c[i][0], s))
		s += c[i][1]
		i -= 1
	print(ans)


import sys
t = int(sys.stdin.readline())
ans = []
for _ in range(t):
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	b = list(map(int, sys.stdin.readline().split()))
	c = sorted(list(zip(a, b)), reverse=True)
	b_time = 0
	for i in range(n):
		b_time += c[i][1]
		if b_time >= c[i][0]:
			b_time = max(c[i][0], b_time - c[i][1])
			break
	ans.append(b_time)
sys.stdout.write('\n'.join(map(str, ans)))


for _ in range(int(input())):
	n = int(input())
	if n == 1:
		print(min(int(input()), int(input())))
		continue
	kur = list(map(int, input().split()))
	sam = list(map(int, input().split()))
	worst = sorted(range(n), key=lambda i: kur[i], reverse=True)
	s = 0
	for w in worst:
		if s + sam[w] < kur[w]:
			s += sam[w]
			kur[w] = 0
		else:
			break
	print(max(s, *kur))


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	X = []
	for i in range(n):
		X.append((A[i], B[i]))
	X.sort()
	S = [0] * (n + 1)
	for i in range(n - 1, -1, -1):
		S[i] = X[i][1] + S[i + 1]
	ANS = min(sum(B), max(A))
	for i in range(n):
		ANS = min(ANS, max(X[i][0], S[i + 1]))
	print(ANS)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = []
	cs = 0
	for i in range(n):
		k = [a[i], b[i]]
		l.append(k)
		cs += b[i]
	l.sort(reverse=True)
	ans = min(l[0][0], cs)
	cs = l[0][1]
	for i in range(1, n):
		ans = min(ans, max(l[i][0], cs))
		cs += l[i][1]
	print(ans)


def binary(x):
	pass

def podschet():
	dp[0] = pairs[0][1]
	for i in range(1, n):
		dp[i] = pairs[i][1] + dp[i - 1]

def sum_na_otr(l):
	if l == 0:
		return dp[n - 1]
	else:
		return dp[n - 1] - dp[l - 1]
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	pairs = [[x, y] for (x, y) in zip(a, b)]
	pairs.sort(key=lambda x: x[0])
	dp = [0] * n
	podschet()
	end = 1000000000000.0
	for i in range(n):
		if i != n - 1:
			ans = max(pairs[i][0], sum_na_otr(i + 1))
		else:
			ans = pairs[i][0]
		end = min(end, ans)
	print(min(end, dp[n - 1]))


import sys
t = int(sys.stdin.readline())
for k in range(t):
	n = int(sys.stdin.readline())
	a = map(int, sys.stdin.readline().split())
	b = map(int, sys.stdin.readline().split())
	zipped = list(zip(a, b))
	zipped.sort()
	i = zipped[-1][0]
	j = 0
	m = 0
	while i > j:
		c = zipped.pop()
		j += c[1]
		if len(zipped) == 0:
			i = 0
		else:
			i = zipped[-1][0]
	d = min(max(i, j), max(c[0], j - c[1]))
	sys.stdout.write('{}\n'.format(d))


import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def get_input(a=str):
	return a(input())

def get_int_input():
	return get_input(int)

def get_input_arr(a):
	return list(map(a, input().split()))

def get_int_input_arr():
	return get_input_arr(int)

def solve():
	t = get_int_input()
	for _ in range(t):
		n = get_int_input()
		a_arr = get_int_input_arr()
		b_arr = get_int_input_arr()
		c = [(a_arr[i], b_arr[i]) for i in range(len(a_arr))]
		c.sort(key=lambda x: x[0])
		suffx_c = [0] * (n + 1)
		for i in range(len(c) - 1, -1, -1):
			suffx_c[i] = suffx_c[i + 1] + c[i][1]
		res = float('inf')
		for i in range(len(c)):
			res = min(res, max(c[i][0], suffx_c[i + 1]))
		res = min(res, suffx_c[0])
		cout << res << endl

def main():
	solve()
main()


import sys
input = sys.stdin.readline

def prog():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		c = [[i, j] for (i, j) in zip(a, b)]
		c.sort(reverse=True)
		min_cost = c[0][0]
		petya_cost = 0
		for i in range(len(c)):
			petya_cost += c[i][1]
			if i != len(c) - 1:
				min_cost = min(min_cost, max(petya_cost, c[i + 1][0]))
			else:
				min_cost = min(min_cost, max(petya_cost, 0))
		print(min_cost)
prog()


import os
import sys
from io import BytesIO, IOBase
import math
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input()) if True else 1):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = []
	for i in range(n):
		l.append((a[i], b[i]))
	l.sort(key=lambda x: x[0])
	bb = list()
	cc = list()
	highestt = 0
	ans = 0
	k = n - 1
	while k > -1:
		if l[k][0] <= ans + l[k][1]:
			vv = max(highestt, l[k][0])
			highestt = vv
			bb.append(vv)
			k -= 1
		else:
			value = l[k][1]
			ans += value
			k -= 1
	rr = 0
	if ans >= highestt:
		rr = ans
	else:
		rr = highestt
	print(rr)


t = int(input())
for i in range(t):
	n = int(input())
	lst1 = list(map(int, input().split()))
	lst2 = list(map(int, input().split()))
	lst3 = []
	for i in range(n):
		lst3.append([lst1[i], lst2[i]])
	lst3 = sorted(lst3)
	for i in range(n):
		lst1[i] = lst3[i][0]
		lst2[i] = lst3[i][1]
	sum1 = sum(lst2)
	sumprev = 0
	ans = sum1
	for i in range(n):
		sumprev += lst2[i]
		ans = min(ans, max(lst1[i], sum1 - sumprev))
	print(ans)


import sys
input = sys.stdin.readline
(inp, ip) = (lambda : int(input()), lambda : [int(w) for w in input().split()])

class ST:

	def __init__(self, arr):
		self.n = len(arr)
		self.st = [0] * (4 * self.n)
		self.build(0, 0, self.n - 1, arr)

	def build(self, si, start, end, arr):
		if start == end:
			self.st[si] = arr[start]
			return
		mid = (start + end) // 2
		self.build(2 * si + 1, start, mid, arr)
		self.build(2 * si + 2, mid + 1, end, arr)
		self.st[si] = max(self.st[2 * si + 1], self.st[2 * si + 2])

	def update(self, i, val):
		self._update(0, 0, self.n - 1, i, val)

	def _update(self, si, start, end, i, val):
		if end < i or i < start:
			return
		if i == start == end:
			self.st[si] = val
			return
		mid = (start + end) // 2
		self._update(2 * si + 1, start, mid, i, val)
		self._update(2 * si + 2, mid + 1, end, i, val)
		self.st[si] = max(self.st[2 * si + 1], self.st[2 * si + 2])

	def query(self, l, r):
		return self._query(0, 0, self.n - 1, l, r)

	def _query(self, si, start, end, l, r):
		if end < l or r < start:
			return 0
		if start >= l and r >= end:
			return self.st[si]
		mid = (start + end) // 2
		m1 = self._query(2 * si + 1, start, mid, l, r)
		m2 = self._query(2 * si + 2, mid + 1, end, l, r)
		return max(m1, m2)
for i in range(inp()):
	n = inp()
	a = ip()
	b = ip()
	new = [[b[i], a[i]] for i in range(n)]
	new.sort(key=lambda i: i[0])
	new.sort(key=lambda i: i[1], reverse=True)
	b = [i[0] for i in new]
	a = [i[1] for i in new]
	c = [0] * n
	c[-1] = a[-1]
	for i in range(n - 2, -1, -1):
		c[i] = max(a[i], c[i + 1])
	st = ST(a)
	ans = sum(b)
	sm = 0
	for i in range(n):
		t = st.query(i, n - 1)
		ans = min(ans, max(sm, t))
		sm += b[i]
	print(ans)


import os
import sys
from io import BytesIO, IOBase
input = sys.stdin.readline

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def OPS(ans):
	sys.stdout.write(str(ans) + '\n')

def OPL(ans):
	[sys.stdout.write(str(_) + ' ') for _ in ans]
	sys.stdout.write('\n')

def main():
	try:
		for _ in range(inp()):
			n = inp()
			a = inlt()
			b = inlt()
			ans = 10 ** 9 + 7
			maxx = 0
			summ = sum(b)
			i = 0
			c = [[b[i], a[j]] for (i, j) in zip(range(n), range(n))]
			c = sorted(c, key=lambda x: x[1])
			while i <= n - 1:
				ans = min(ans, max(maxx, summ))
				summ -= c[i][0]
				maxx = max(maxx, c[i][1])
				i += 1
				ans = min(ans, max(summ, maxx))
			OPS(ans)
	except Exception as e:
		print(e)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys

def get_ans(time_pairs):
	s = 0
	for (delivery_time, walk_time) in time_pairs:
		if s + walk_time < delivery_time:
			s += walk_time
		else:
			s = max(s, delivery_time)
			break
	return s

def get_ans2(time_pairs):
	n = len(time_pairs)
	b = [0] * n
	glob_max = 1111111111
	while True:
		i = 0
		deliv_max = 0
		walk_sum = 0
		for (delivery_time, walk_time) in time_pairs:
			if b[i]:
				if delivery_time > deliv_max:
					deliv_max = delivery_time
			else:
				walk_sum += walk_time
			i += 1
		glob_max = min(glob_max, max(deliv_max, walk_sum))
		if sum(b) == n:
			break
		i = 0
		while b[i] == 1:
			b[i] = 0
			i += 1
		b[i] = 1
	return glob_max
input = sys.stdin.readline
t = int(input())
ok = 0
for _ in range(t):
	input()
	delivery_times = [int(v) for v in input().split()]
	walk_times = [int(v) for v in input().split()]
	time_pairs = list(reversed(sorted(zip(delivery_times, walk_times))))
	print(get_ans(time_pairs))
sys.stdin.close()


import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from bisect import *
from math import sqrt, pi, ceil, log, inf, gcd
from itertools import permutations
from copy import deepcopy
from heapq import *
from sys import setrecursionlimit

def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		c = []
		for i in range(n):
			c.append([a[i], b[i]])
		c.sort(reverse=True, key=lambda x: x[0])
		mi = inf
		z = 0
		for i in range(n):
			mi = min(c[i][0] + max(0, z - c[i][0]), mi)
			z += c[i][1]
		mi = min(mi, z)
		print(mi)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


ans = []
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	if n == 1:
		ans.append(min(a[0], b[0]))
		continue
	c = [[a[i], b[i]] for i in range(n)]
	c.sort(key=lambda x: (x[0], x[1] * -1), reverse=True)
	time = 0
	for i in range(n - 1):
		if time + c[i][1] >= c[i + 1][0]:
			ans.append(min(c[i][0], time + c[i][1]))
			break
		time += c[i][1]
	else:
		ans.append(min(c[-1][0], time + c[-1][1]))
print('\n'.join((str(x) for x in ans)))


def solve(n, a, b):

	def ok(t):
		total = 0
		for i in range(n):
			if a[i] > t:
				total += b[i]
		return total <= t
	le = 0
	ri = 10 ** 9
	while le < ri:
		mid = (le + ri) // 2
		if ok(mid):
			ri = mid
		else:
			le = mid + 1
	return le
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	print(solve(n, a, b))


from sys import stdin, stdout
for i in range(int(stdin.readline().strip())):
	n = int(stdin.readline().strip())
	a = list(map(int, stdin.readline().strip().split()))
	b = list(map(int, stdin.readline().strip().split()))
	k = list(zip(a, b))
	k.sort()
	k = k[::-1]
	s = k[0][0]
	t = 0
	for i in range(n - 1):
		t += k[i][1]
		s = min(s, max(k[i + 1][0], t))
	print(min(s, t + k[-1][1]))


import sys
t = int(input())
input = sys.stdin.readline
for _ in range(t):
	n = int(input())
	a = list(map(int, input().strip(' ').split(' ')))
	b = list(map(int, input().strip(' ').split(' ')))
	if n == 1:
		print(min(a[0], b[0]))
		continue
	arr = [(i, j) for (i, j) in zip(a, b)]
	arr.sort()
	her_time = 0
	while arr and her_time + arr[-1][1] < arr[-1][0]:
		her_time += arr.pop()[1]
	if arr:
		print(max(arr[-1][0], her_time))
	else:
		print(her_time)


a = int(input())
for i in range(a):
	n = int(input())
	z = list(map(int, input().split()))
	m = list(map(int, input().split()))
	q = sum(m)
	ans = []
	for i in range(len(z)):
		ans.append([z[i], m[i]])
	ans.sort()
	total = [q - ans[0][1]]
	for i in range(1, len(ans)):
		total.append(total[-1] - ans[i][1])
	maxa = min(ans[-1][0], q)
	for i in range(len(ans)):
		maxa = min(maxa, max(ans[i][0], total[i]))
	print(maxa)


from sys import stdin, stdout
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	s = 0
	ss = 0
	l = []
	for i in range(n):
		l.append([a[i], b[i]])
	l.sort()
	kkk = sum([l[j][1] for j in range(n)])
	kk = kkk
	for i in range(n):
		kkk -= l[i][1]
		bb = max(l[i][0], kkk)
		if kk > bb:
			kk = bb
	print(kk)


import os, sys
from collections import defaultdict, Counter, deque
from io import BytesIO, IOBase
from math import gcd, inf

def coun(a, p, n):
	c = 0
	for i in range(n):
		if a[i] & 1 << p:
			c += 1
	return c

def main():
	for _ in range(int(input())):
		n = int(input())
		a = [int(x) for x in input().split()]
		b = [int(x) for x in input().split()]
		x = []
		for i in range(n):
			x.append([a[i], b[i]])
		x.sort()
		if x[-1][0] <= x[-1][1]:
			print(x[-1][0])
		else:
			for j in range(n - 2, -1, -1):
				x[j][1] = x[j][1] + x[j + 1][1]
			m = min(x[n - 1][0], x[0][1])
			for j in range(n - 2, -1, -1):
				if max(x[j + 1][1], x[j][0]) < m:
					m = max(x[j + 1][1], x[j][0])
			print(m)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from collections import defaultdict
from functools import reduce
from bisect import bisect_right
from bisect import bisect_left
import copy

def main():
	for _ in range(int(input())):
		n = int(input())
		d = defaultdict(list)
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		for i in range(n):
			d[i].append(a[i])
			d[i].append(b[i])
		delivery = []
		takeaway = []
		for (key, value) in sorted(d.items(), key=lambda e: e[1][0]):
			delivery.append(value[0])
			takeaway.append(value[1])
		for i in range(n - 2, -1, -1):
			takeaway[i] += takeaway[i + 1]
		mini = min(delivery[n - 1], takeaway[0])
		for i in range(n - 1):
			mini = min(mini, max(delivery[i], takeaway[i + 1]))
		print(mini)
main()


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
start_time = time.time()

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def getMat(n):
	return [getInts() for _ in range(n)]
MOD = 998244353

def get_ints():
	return map(int, sys.stdin.readline().split())
T = int(input())
for _ in range(T):
	n = int(input())
	a = list(get_ints())
	b = list(get_ints())
	arr = []
	for i in range(n):
		arr.append([a[i], b[i]])
	arr = sorted(arr, key=lambda x: x[0])
	summ = 0
	total_summ = sum(b)
	for i in range(n):
		summ += arr[i][1]
		arr[i][1] = summ
	ans = 10 ** 18
	for i in range(n):
		ans = min(max(arr[i][0], summ - arr[i][1]), ans)
	print(min(ans, summ))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ans = sum(b)
	res = ans
	b = [x for (_, x) in sorted(zip(a, b))]
	a.sort()
	for i in range(1, n):
		b[i] = b[i] + b[i - 1]
	for i in range(n):
		x = max(ans - b[i], a[i])
		res = min(res, x)
	print(res)


t = int(input())

def solve(n, a, b):
	aa = [(x, i) for (i, x) in enumerate(a)]
	aa.sort()
	aa.reverse()
	pick = 0
	start = 0
	while start < n and pick < aa[start][0]:
		pick += b[aa[start][1]]
		start += 1
	print(min(aa[start - 1][0], pick))
for i in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	b = list(map(int, input().split(' ')))
	solve(n, a, b)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush, heappop, heapify
from itertools import permutations, combinations
mod = int(1000000000.0) + 7
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
out = lambda x: stdout.write(str(x) + '\n')
t = ip()
for _ in range(t):
	n = ip()
	a = list(inp())
	b = list(inp())
	(a, b) = zip(*sorted(zip(a, b)))
	a = list(a)
	b = list(b)
	ch = a[-1]
	ct = 0
	ans = [a[-1]]
	for i in range(n - 1, -1, -1):
		if ct + b[i] <= a[i]:
			ct += b[i]
			if i == 0:
				ans.append(ct)
				break
			else:
				ans.append(max(ct, a[i - 1]))
		else:
			break
	ans = min(ans)
	out(ans)


t = int(input())
while t:
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	comb = []
	flag = 0
	for (i, val) in enumerate(a):
		comb.append([a[i], b[i]])
	comb.sort()
	for i in range(n - 2, -1, -1):
		comb[i][1] = comb[i][1] + comb[i + 1][1]
	if comb[0][0] >= comb[0][1]:
		print(comb[0][1])
		t -= 1
		continue
	for i in range(1, n):
		if comb[i][0] >= comb[i][1]:
			print(max(comb[i][1], comb[i - 1][0]))
			flag = 1
			break
	if not flag:
		print(comb[-1][0])
	t -= 1


import sys
input = sys.stdin.readline
(inp, ip) = (lambda : int(input()), lambda : [int(w) for w in input().split()])
for i in range(inp()):
	n = inp()
	a = ip()
	b = ip()
	new = [[b[i], a[i]] for i in range(n)]
	new.sort(key=lambda i: i[0])
	new.sort(key=lambda i: i[1], reverse=True)
	b = [i[0] for i in new]
	a = [i[1] for i in new]
	c = [0] * n
	c[-1] = a[-1]
	for i in range(n - 2, -1, -1):
		c[i] = max(a[i], c[i + 1])
	ans = sum(b)
	sm = 0
	for i in range(n):
		t = c[i]
		ans = min(ans, max(sm, t))
		sm += b[i]
	print(ans)


t = int(input())
p = []
for i in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(y) for y in input().split()]
	if n == 1:
		p.append(min(a[0], b[0]))
	else:
		c = []
		for i in range(n):
			c.append((a[i], b[i]))
		c.sort(key=lambda x: x[0], reverse=True)
		d = []
		e = 0
		for j in range(n):
			e += c[j][1]
			d.append(e)
		f = 0
		while d[f] <= c[f][0]:
			if f == n - 1:
				break
			f += 1
		if n == 2:
			if f == 0:
				p.append(c[0][0])
			elif d[1] <= c[1][0]:
				p.append(d[1])
			else:
				p.append(max(c[1][0], d[0]))
		elif f == 0:
			p.append(c[0][0])
		elif f == n - 1:
			if d[n - 1] <= c[n - 1][0]:
				p.append(d[n - 1])
			else:
				p.append(max(c[n - 1][0], d[n - 2]))
		else:
			p.append(max(c[f][0], d[f - 1]))
for x in p:
	print(x)


import os, sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import ceil
mod = 10 ** 9 + 7
for _ in range(int(input())):
	n = int(input())
	courier = list(map(int, input().split()))
	pickup = list(map(int, input().split()))
	info = [[courier[i], pickup[i]] for i in range(n)]
	info.sort()
	for i in range(n - 1, -1, -1):
		if i == n - 1:
			continue
		else:
			info[i][1] += info[i + 1][1]
	min_time = float('inf')
	for i in range(n - 1):
		temp_ans = max(info[i][0], info[i + 1][1])
		min_time = min(min_time, temp_ans)
	min_time = min(min_time, min(info[-1][0], info[0][1]))
	print(min_time)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = []
	for i in range(n):
		l.append((a[i], b[i]))
	l.sort()
	sm = sum(b)
	(ans, s) = (sm, 0)
	for i in range(n):
		s += l[i][1]
		ans = min(ans, max(l[i][0], sm - s))
	print(ans)


import sys
input = sys.stdin.readline
R = lambda : map(int, input().split())
(t,) = R()
for _ in [0] * t:
	R()
	s = 0
	ans = 0
	for (x, y) in sorted(zip(R(), R()), reverse=True):
		if ans > x:
			break
		if ans + y >= x:
			ans = x
			break
		ans += y
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	restaurants = map(int, input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	cmb = list(zip(a, b))
	sorted_cmb = sorted(cmb, key=lambda x: (-x[0], x[0]))
	k = 0
	restaurant = 0
	for (courier, pickUp) in sorted_cmb:
		if k + pickUp < courier:
			k += pickUp
		else:
			print(max(k, courier))
			break
	else:
		print(k)


def testcase():
	n = int(input())
	arr = list(map(int, input().split()))
	brr = list(map(int, input().split()))
	data = []
	for i in range(n):
		data.append([arr[i], brr[i]])
	data.sort(key=lambda x: x[0], reverse=True)
	s = 0
	for i in range(n):
		(a, b) = data[i]
		if s + b >= a:
			print(max(s, a))
			return
		s += b
	print(s)
	return
import sys, os
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
sys.setrecursionlimit(10 ** 5)
t = int(input())
for _ in range(t):
	testcase()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	(ordA, ordB) = zip(*sorted(zip(a, b)))
	if ordA[-1] <= ordB[-1]:
		print(ordA[-1])
	else:
		ans = 0
		for i in range(n - 1, -1, -1):
			if ans > ordA[i]:
				break
			ans = min(ans + ordB[i], ordA[i])
		print(ans)


input = __import__('sys').stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = []
	for i in range(n):
		c.append([a[i], b[i]])
	c.sort(reverse=True)
	ans = 0
	for (x, y) in c:
		if ans + y < x:
			ans += y
		else:
			ans = max(x, ans)
			break
	print(ans)


import math
import collections
t = int(input())
for w in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	s = sum(a) + sum(b)
	d = {}
	for i in range(n):
		if a[i] in d:
			d[a[i]] += b[i]
		else:
			d[a[i]] = b[i]
	d = collections.OrderedDict(sorted(d.items(), reverse=True))
	l1 = [0]
	j = 0
	for i in d:
		l1.append(l1[j] + d[i])
		j += 1
	j = 0
	s = min(s, l1[-1])
	for i in d:
		s = min(s, max(l1[j], i))
		j += 1
	print(s)


def solve(a, b, n, ans):
	arr = []
	total = 0
	for i in range(n):
		arr.append((a[i], b[i]))
		total += b[i]
	arr.sort()
	min_val = total
	for i in range(n):
		total -= arr[i][1]
		min_val = min(min_val, max(arr[i][0], total))
	ans.append(str(min_val))

def main():
	t = int(input())
	ans = []
	for i in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		solve(a, b, n, ans)
	print('\n'.join(ans))
main()


time = []
t = int(input())
while t:
	t -= 1
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	if n == 1:
		time.append(min(a[0], b[0]))
		continue
	else:
		c = sorted(list(zip(a, b)), reverse=True)
		y = 0
		ti = 0
		for i in range(n):
			if y + c[i][1] < c[i][0]:
				y += c[i][1]
				ti = max(ti, y)
			else:
				ti = max(ti, c[i][0])
		time.append(ti)
print('\n'.join(map(str, time)))


n = int(input())
total = []
for i in range(n):
	dishes = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	l1 = sorted(zip(a, b))
	pickup = sum(b)
	mintime = pickup
	for t in l1:
		pickup -= t[1]
		mintime = min(mintime, max(t[0], pickup))
	total.append(mintime)
for k in total:
	print(k)


import math
import sys, bisect
from heapq import *
from itertools import *
from collections import *
sys.setrecursionlimit(10 ** 6)
I = lambda : int(sys.stdin.readline())
neo = lambda : map(int, sys.stdin.readline().split())
Neo = lambda : list(map(int, sys.stdin.readline().split()))
for _ in range(I()):
	n = I()
	A = Neo()
	B = Neo()
	Ans = []
	for (i, j) in zip(A, B):
		Ans += [(i, j)]
	Ans.sort()
	t = 0
	for (i, j) in Ans[::-1]:
		p = t + j
		if p >= i:
			t = max(t, i)
			break
		else:
			t = p
	print(t)


import os
import sys
from io import BytesIO, IOBase
_str = str
BUFSIZE = 8192

def str(x=b''):
	return x if type(x) is bytes else _str(x).encode()

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def inp():
	return sys.stdin.readline().rstrip()

def mpint():
	return map(int, inp().split(' '))

def itg():
	return int(inp())

def solve():
	n = itg()
	aa = tuple(mpint())
	bb = tuple(mpint())
	delivery = walk = 0
	for (a, b) in sorted(zip(aa, bb), reverse=True):
		if walk + b >= a:
			delivery = a
			break
		walk += b
	return max(delivery, walk)

def main():
	for _ in range(itg()):
		print(solve())
DEBUG = 0
URL = 'https://codeforces.com/contest/1443/problem/C'
if DEBUG == 1:
	import requests
	from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
	runner = TestCaseRunner(main, URL)
	inp = runner.input_stream
	print = runner.output_stream
	runner.checking()
elif DEBUG == 2:
	main()
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	main()


from collections import defaultdict as dd
for i in range(int(input())):
	n = int(input())
	l1 = list(map(int, input().split()))
	l2 = list(map(int, input().split()))
	d = dd(int)
	l = []
	for j in range(n):
		d[l1[j]] += l2[j]
	for j in d:
		l.append([j, d[j]])
	l.sort(reverse=True)
	a = l[0][0]
	b = 0
	ans = a
	for j in range(len(l)):
		if a == l[j][0]:
			if j < len(l) - 1:
				if ans > max(l[j + 1][0], b + l[j][1]):
					ans = max(l[j + 1][0], b + l[j][1])
					b += l[j][1]
					a = l[j + 1][0]
			elif a > b + l[j][1]:
				ans = b + l[j][1]
				b += l[j][1]
	print(ans)


import sys
input = sys.stdin.buffer.readline

def solution():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = [[0, 0]]
	for i in range(n):
		l.append([a[i], -b[i]])
	l.sort(reverse=True)
	cnt = 0
	i = 0
	while i < n:
		if cnt + abs(l[i][1]) < l[i][0]:
			cnt += abs(l[i][1])
		else:
			break
		i += 1
	print(max(l[i][0], cnt))
t = int(input())
for _ in range(t):
	solution()


def func(a, b):
	c = sorted(list(zip(a, b)), reverse=True)
	d = 0
	for j in range(n):
		d += c[j][1]
		if d >= c[j][0]:
			d = max(c[j][0], d - c[j][1])
			break
	ans[i] = str(d)
m = int(input())
ans = [0] * m
for i in range(m):
	n = int(input())
	if n == 1:
		a = int(input())
		b = int(input())
		ans[i] = str(min(a, b))
		continue
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	func(a, b)
print('\n'.join(ans))


import os
from heapq import heapify, heappop, heappush
import sys
import sys, threading
import math
import operator
import bisect
from collections import defaultdict
from io import BytesIO, IOBase
sys.setrecursionlimit(10 ** 5)

def inpt():
	return [int(k) for k in input().split()]

def main():
	for _ in range(int(input())):
		n = int(input())
		ar = inpt()
		br = inpt()
		for i in range(n):
			ar[i] = (ar[i], br[i])
		ar.sort(key=lambda x: [-x[0], -x[1]])
		ans = 0
		for (i, j) in ar:
			if ans + j < i:
				ans += j
			else:
				ans = max(ans, i)
				break
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


n = int(input())
ans = []
for i in range(n):
	m = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = sorted(list(zip(a, b)), reverse=True)
	d = 0
	for i in range(m):
		d += c[i][1]
		if d >= c[i][0]:
			d = max(c[i][0], d - c[i][1])
			break
	ans.append(d)
print('\n'.join(map(str, ans)))


import sys
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	res = float('inf')
	c = [[i, j] for (i, j) in zip(a, b)]
	c.sort()
	for i in range(1, n):
		c[i][1] += c[i - 1][1]
	res = c[n - 1][1]
	for i in range(n):
		res = min(res, max(c[i][0], c[n - 1][1] - c[i][1]))
	print(res)


for t in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	final = [[a[i], b[i]] for i in range(n)]
	deliver_sorted = sorted(final, key=lambda x: x[0], reverse=True)
	deliver = 0
	self = 0
	for i in range(n):
		if self + deliver_sorted[i][1] < max(deliver, deliver_sorted[i][0]):
			self += deliver_sorted[i][1]
		else:
			deliver = max(deliver, deliver_sorted[i][0])
	ans = max(deliver, self)
	print(ans)


t = int(input())
m = []
for i in range(t):
	order = int(input())
	d = list(map(int, input().split()))
	p = list(map(int, input().split()))
	z = sorted(list(zip(d, p)))
	s = sum(p)
	for j in range(order):
		f = z[j][0]
		if s > f:
			s -= z[j][1]
			s = max(f, s)
	m.append(s)
print('\n'.join(map(str, m)))


for ct in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	d = list(zip(a, b))
	d.sort(reverse=True)
	d.append((0, 0))
	soma = 0
	for i in range(n):
		if soma + d[i][1] > d[i][0]:
			print(max(soma, d[i][0]))
			break
		else:
			soma += d[i][1]
	else:
		print(soma)


import sys
for _ in range(int(sys.stdin.readline())):
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	b = list(map(int, sys.stdin.readline().split()))
	temp = []
	for i in range(n):
		temp.append([a[i], b[i]])
	temp.sort()
	s = 0
	ans = 0
	for i in range(n - 1, -1, -1):
		if s + temp[i][1] < temp[i][0]:
			s += temp[i][1]
			ans = s
		else:
			ans = max(temp[i][0], s)
			break
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	arr = [[b[i], a[i]] for i in range(n)]
	arr = sorted(arr, key=lambda x: x[0])
	arr = sorted(arr, key=lambda x: x[1], reverse=True)
	t = sum(b)
	ans = t
	maxx = 0
	for i in range(n - 1, -1, -1):
		maxx = max(maxx, arr[i][1])
		t -= arr[i][0]
		c = max(t, maxx)
		ans = min(ans, c)
	print(ans)


t = int(input())
lans = ''
for _ in range(t):
	n = int(input())
	if n == 1:
		lans += str(min(int(input()), int(input()))) + '\n'
		continue
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	ls = []
	for i in range(n):
		ls.append([a[i], b[i]])
	ls.sort(reverse=True)
	ans = ls[0][0]
	time = 0
	for i in range(0, n):
		time += ls[i][1]
		if i == n - 1:
			ans = min(ans, time)
			break
		q = max(time, ls[i + 1][0])
		if ans >= q:
			ans = q
		else:
			break
	lans += str(ans) + '\n'
print(lans)


from sys import stdin
from math import inf
input = lambda : stdin.readline().strip()
wtf = int(input())
for i in range(wtf):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))

	def f(m):
		ans = 0
		for i in range(n):
			if a[i] > m:
				ans += b[i]
		return ans
	l = 0
	r = max(a)
	while r - l > 1:
		m = (r + l) // 2
		d = f(m)
		if f(m) > m:
			l = m
		else:
			r = m
	print(r)


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	c = dict()
	x = 0
	for i in range(n):
		if a[i] not in c:
			c[a[i]] = b[i]
		else:
			c[a[i]] += b[i]
	d = sorted(c, reverse=True)
	for i in d:
		if i > x + c[i]:
			x = x + c[i]
		elif x >= i:
			x = x
		else:
			x = i
			break
	print(x)


import sys
from math import *
from fractions import *

def main():

	def modst(a, s):
		ret = 1
		while s:
			if s % 2:
				ret = ret * a % mod
			a = a * a % mod
			s //= 2
		return ret

	def C_n_k(n, k):
		return fact[n] * modst(fact[n - k] * fact[k] % mod, mod - 2) % mod
	n = int(sys.stdin.readline().strip())
	q = list(map(int, sys.stdin.readline().split()))
	w = list(map(int, sys.stdin.readline().split()))
	t = sorted([[0, 0]] + [[q[i], w[i]] for i in range(n)])
	p = [0] * (n + 7)
	for i in range(n, -1, -1):
		p[i] = p[i + 1] + t[i][1]
	print(min([max(t[i][0], p[i + 1]) for i in range(n + 1)]))
for i in range(int(sys.stdin.readline().strip())):
	main()


import os
import sys
from io import BytesIO, IOBase
arr = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397]
from collections import defaultdict
from math import sqrt
import math

def solution():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	arr = []
	for i in range(n):
		arr.append([a[i], b[i]])
	arr.sort()
	asum = [0] * (n + 1)
	s = 0
	for i in range(n):
		s = max(s, arr[i][0])
		asum[i + 1] = s
	s = 0
	bsum = [0] * (n + 1)
	for i in reversed(range(n)):
		s += arr[i][1]
		bsum[i] = s
	minsofar = math.inf
	for i in range(n + 1):
		minsofar = min(minsofar, max(asum[i], bsum[i]))
	print(minsofar)

def main():
	testcases = 1
	testcases = int(input())
	for _ in range(testcases):
		solution()
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for tt in range(int(input())):
	n = int(input())
	a = [[0] * 2 for i in range(n)]
	b = list(map(int, input().split()))
	c = list(map(int, input().split()))
	for i in range(n):
		a[i] = [b[i], c[i]]
	suff = 0
	ans = float('inf')
	a.sort()
	for i in range(n - 1, -1, -1):
		ans = min(ans, a[i][0] + max(0, suff - a[i][0]))
		suff += a[i][1]
	print(min(ans, suff))


import sys
input = sys.stdin.readline
ansl = []
for _ in range(int(input())):
	n = int(input())
	al = list(map(int, input().split()))
	bl = list(map(int, input().split()))
	abl = []
	for i in range(n):
		abl.append((al[i], bl[i]))
	abl.sort(reverse=True, key=lambda x: x[0])
	deli_c = abl[0][0]
	pic_c = 0
	ans = deli_c
	for i in range(n):
		deli_c = abl[i + 1][0] if i + 1 < n else 0
		pic_c += abl[i][1]
		ans = min(ans, max(deli_c, pic_c))
	ansl.append(ans)
for a in ansl:
	print(a)


import sys, math, itertools, collections, copy
input = sys.stdin.readline
INF = 10 ** 18 + 20

def solve():
	N = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	prefix = [0]
	pairs = []
	for i in range(N):
		pairs.append([a[i], b[i]])
	pairs.sort(key=lambda x: (x[0], x[1]))
	for i in range(N):
		prefix.append(prefix[-1] + pairs[i][1])
	ans = INF
	ans = min(ans, prefix[-1] - prefix[0])
	for i in range(N):
		ans = min(ans, max(pairs[i][0], prefix[-1] - prefix[i + 1]))
	print(ans)
for _ in range(int(input())):
	solve()


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()
import sys
input = sys.stdin.readline
scanner = lambda : int(input())
string = lambda : input().rstrip()
get_list = lambda : list(read())
read = lambda : map(int, input().split())
get_float = lambda : map(float, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def lcm(a, b):
	return a * b // math.gcd(a, b)

def is_integer(n):
	return math.ceil(n) == math.floor(n)

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	if y == 0:
		return 1
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	(prime[0], prime[1]) = (False, False)
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def next_prime(n, primes):
	while primes[n] != True:
		n += 1
	return n
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

def factors(n):
	res = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			res.append(i)
			res.append(n // i)
	return list(set(res))

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

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

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(moves, n):
	val = (moves + 1) // 2
	rem = moves - val
	sol = (val + 1) * (rem + 1)
	return sol < n

def sortSecond(val):
	return val[1]
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
alphs = 'abcdefghijklmnopqrstuvwxyz'
from itertools import permutations
import math
import bisect as bis
import random
import sys
import collections as collect
import functools as fnt
from decimal import Decimal

def solve():
	n = scanner()
	a = get_list()
	b = get_list()
	pair = [[x, y] for (x, y) in zip(a, b)]
	pair.sort()
	storage = [0] * (n + 5)
	for i in range(n - 1, -1, -1):
		storage[i] = storage[i + 1] + pair[i][1]
	ans = storage[0]
	for i in range(n):
		ans = min(ans, max(storage[i + 1], pair[i][0]))
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = scanner()
for i in range(t):
	solve()


t = int(input())
res = []
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	arr = []
	for j in range(n):
		arr.append([a[j], b[j]])
	arr.sort(reverse=True)
	temp = 0
	for j in range(n):
		temp += arr[j][1]
		if temp > arr[j][0]:
			res.append(max(temp - arr[j][1], arr[j][0]))
			break
		if j == n - 1:
			res.append(temp)
for i in res:
	print(i)


from sys import stdin, stdout
input = stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	temp = []
	for i in range(n):
		temp.append((a[i], b[i]))
	temp = sorted(temp, key=lambda x: x[1])
	temp = sorted(temp, key=lambda x: x[0], reverse=True)
	ans = temp[0][0]
	ans2 = 0
	for i in range(n):
		ans2 += temp[i][1]
		if i == n - 1:
			if ans > max(0, ans2):
				ans = max(0, ans2)
			elif ans < max(0, ans2):
				break
			break
		if ans > max(temp[i + 1][0], ans2):
			ans = max(temp[i + 1][0], ans2)
		elif ans < max(temp[i + 1][0], ans2):
			break
	print(ans)


from sys import stdin
from math import *

def check(n):
	s = 0
	for i in range(len(a)):
		if a[i] > n:
			s += b[i]
	return max(s, n)
for __ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	x = 0
	y = max(a)
	ans = -1
	while x <= y:
		m = (x + y) // 2
		if check(m) > m:
			x = m + 1
		else:
			ans = m
			y = m - 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	ass = [int(i) for i in input().split()]
	bss = [int(i) for i in input().split()]
	whole = [(ass[i], bss[i]) for i in range(n)]
	whole.sort()
	ans = 100000000000
	bsum = sum(bss)
	bcur = 0
	for i in whole:
		(a, b) = i
		bcur += b
		if max(a, bsum - bcur) < ans:
			ans = max(a, bsum - bcur)
	print(min(ans, bsum))


import sys
input = sys.stdin.readline
from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	lis = list(zip(a, b))
	lis.sort()
	suf = [0]
	lis.reverse()
	suf[0] = lis[0][1]
	for (i, j) in lis[1:]:
		suf.append(suf[-1] + j)
	suf.reverse()
	suf.append(0)
	lis.reverse()
	c = 10 ** 15
	for i in range(n):
		c = min(c, max(lis[i][0], suf[i + 1]))
	c = min(c, suf[0])
	print(c)


def mergesort(arr, si, ei, arr2):
	if si == ei:
		return ([arr[si]], [arr2[si]])
	mid = (si + ei) // 2
	(a, a2) = mergesort(arr, si, mid, arr2)
	(b, b2) = mergesort(arr, mid + 1, ei, arr2)
	ans = []
	ans2 = []
	i = 0
	j = 0
	la = len(a)
	lb = len(b)
	while i < la and j < lb:
		if a[i] > b[j]:
			ans.append(a[i])
			ans2.append(a2[i])
			i += 1
		else:
			ans.append(b[j])
			ans2.append(b2[j])
			j += 1
	while i < la:
		ans.append(a[i])
		ans2.append(a2[i])
		i += 1
	while j < lb:
		ans.append(b[j])
		ans2.append(b2[j])
		j += 1
	return (ans, ans2)
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = [int(s) for s in input().split()]
	b = [int(s) for s in input().split()]
	(a, b) = mergesort(a, 0, n - 1, b)
	result = []
	gosum = 0
	for i in range(n):
		if a[i] > b[i]:
			if a[i] > gosum + b[i]:
				gosum += b[i]
				result.append(gosum)
			else:
				result.append(a[i])
		else:
			result.append(a[i])
	print(max(result))


import time, math as mt, bisect as bs, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def sieve():
	li = [True] * (2 * 10 ** 5 + 5)
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(2 * 10 ** 5 + 5):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count
mx = 10 ** 7
spf = [mx] * (mx + 1)

def SPF():
	spf[1] = 1
	for i in range(2, mx + 1):
		if spf[i] == mx:
			spf[i] = i
			for j in range(i * i, mx + 1, i):
				if i < spf[j]:
					spf[j] = i
	return

def readTree(n, e):
	adj = [set() for i in range(n + 1)]
	for i in range(e):
		(u1, u2) = IP()
		adj[u1].add(u2)
	return adj
mod = 10 ** 9 + 7

def solve():
	n = II()
	a = L()
	b = L()
	li = []
	for i in range(n):
		li.append([a[i], b[i]])
	li.sort(key=lambda x: x[0])
	pref = [0] * n
	pref[0] = li[0][1]
	for i in range(1, n):
		pref[i] = pref[i - 1] + li[i][1]
	ans = 1e+19
	for i in range(n):
		ans = min(ans, max(li[i][0], pref[n - 1] - pref[i]))
	ans = min(ans, pref[n - 1])
	print(ans)
	return
t = II()
for i in range(t):
	solve()


import functools

def cmp(a, b):
	if a[0] == b[0]:
		return -1 if a[1] < b[1] else 1
	return -1 if a[0] < b[0] else 1

def main():
	t = int(input())
	ans = []
	for _ in range(t):
		n = int(input())
		a = map(int, input().split())
		b = map(int, input().split())
		a = list(a)
		s = sum(a)
		arr = zip(a, b)
		arr = sorted(arr, key=functools.cmp_to_key(cmp))
		i = n - 1
		st = 0
		while i >= 0:
			if st > arr[i][0]:
				break
			s -= arr[i][0]
			st += arr[i][1]
			i -= 1
		ans.append(str(min(arr[i + 1][0], st)))
	print('\n'.join(ans))
main()


import os, sys
from io import BytesIO, IOBase

class Node:

	def __init__(self, tak, cou):
		self.tak = tak
		self.cou = cou

def main():
	for _ in range(int(input())):
		n = int(input())
		arr = [Node(b, a) for (a, b) in zip(map(int, input().split()), map(int, input().split()))]
		arr.sort(key=lambda y: y.cou)
		ans = 10 ** 20
		val = 0
		for i in range(n - 1, -1, -1):
			ans = min(ans, max(arr[i].cou, val))
			val += arr[i].tak
		print(min(ans, val))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c for j in range(b)] for i in range(a)]

def list3d(a, b, c, d):
	return [[[d for k in range(c)] for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e for l in range(d)] for k in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
EPS = 10 ** (-10)
for _ in range(INT()):
	N = INT()
	A = LIST()
	B = LIST()
	AB = list(zip(A, B))
	AB.sort()
	accmx = [0] * (N + 1)
	acc = [0] * (N + 1)
	for i in range(N):
		accmx[i + 1] = max(accmx[i], AB[i][0])
	for i in range(N - 1, -1, -1):
		acc[i] = acc[i + 1] + AB[i][1]
	ans = INF
	for i in range(N + 1):
		ans = min(ans, max(acc[i], accmx[i]))
	print(ans)


n = int(input())
output = []
for i in range(n):
	m = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	l = [[0] * 2 for i in range(m)]
	for j in range(m):
		l[j][0] = a[j]
		l[j][1] = b[j]
	l.sort(key=lambda x: x[0], reverse=True)
	t = l[0][0]
	s = 0
	for j in range(m - 1):
		s += l[j][1]
		t = min(t, max(s, l[j + 1][0]))
	output.append(str(min(t, s + l[m - 1][1])))
print('\n'.join(output))


import sys, io, os, time
from collections import defaultdict
from collections import Counter
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect, math, heapq
alphabet = 'abcdefghijklmnopqrstuvwxyz'
input = sys.stdin.readline
for ii in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = 1
	r = 10 ** 10

	def possible(m):
		global a
		done = [False] * n
		for i in range(n):
			if a[i] <= m:
				done[i] = True
		rem = 0
		for i in range(n):
			if not done[i]:
				rem += b[i]
		return rem <= m
	while l < r:
		mid = (r + l) // 2
		if possible(mid):
			r = mid
		else:
			l = mid + 1
	print(l)


def calculate(li1, li2):
	length = len(li1)
	c = [[li1[i], li2[i]] for i in range(length)]
	c.sort(key=lambda x: (-x[0], x[1]))
	c.append([0, 0])
	(pick, diliver, j) = (0, c[0][0], 0)
	while pick + c[j][1] <= c[j][0] and j < length:
		pick += c[j][1]
		diliver = c[j + 1][0]
		j += 1
	return max(diliver, pick)
n = int(input())
l = [[]] * n
for i in range(n):
	length0 = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	l[i] = [a, b]
for j in range(n):
	print(calculate(l[j][0], l[j][1]))


import sys
t = int(sys.stdin.readline().strip())
for j in range(t):
	n = int(sys.stdin.readline().strip())
	a = list(map(int, sys.stdin.readline().strip().split()))
	b = list(map(int, sys.stdin.readline().strip().split()))
	a_s = sorted(enumerate(a), key=lambda i: i[1])
	i = len(a_s) - 1
	not_stop = True
	B = 0
	while i >= 0:
		(p, val) = a_s[i]
		if B + b[p] > val:
			break
		B += b[p]
		i -= 1
	if i >= 0:
		new_best = max(B, a_s[i][1])
	else:
		new_best = B
	print(new_best)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ind = sorted(list(range(n)), key=lambda k: a[k])
	ind.reverse()
	res = 0
	l = -1
	for i in range(n):
		k = ind[i]
		if res + b[k] >= a[k]:
			break
		res += b[k]
		l = i
	if l < n - 1:
		print(max(res, a[ind[l + 1]]))
	else:
		print(res)


from math import *
from bisect import *
from collections import *
from random import *
from decimal import *
import sys
input = sys.stdin.readline

def inp():
	return int(input())

def st():
	return input().rstrip('\n')

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

def ma():
	return map(int, input().split())
t = inp()
while t:
	t -= 1
	n = inp()
	a = lis()
	b = lis()
	r = []
	for i in range(n):
		r.append([a[i], i])
	r.sort(reverse=True)
	pre = []
	for i in range(n):
		if i == 0:
			pre.append(b[r[i][1]])
		else:
			pre.append(pre[-1] + b[r[i][1]])
	res = float('inf')
	for i in range(n):
		if i == 0:
			res = min(res, r[i][0])
		else:
			res = min(res, max(r[i][0], pre[i - 1]))
	res = min(res, pre[-1])
	print(res)


import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	n = int(input())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	C = []
	for i in range(n):
		C.append([A[i], B[i]])
	C.sort(reverse=True)
	v2 = 0
	ans = C[0][0]
	for i in range(n):
		v2 = v2 + C[i][1]
		if C[i][0] > v2:
			ans = min(v2, C[i][0])
		else:
			ans = max(ans, C[i][0])
			break
	print(ans)


import sys
input = sys.stdin.readline

def f(x):
	ans = 0
	for i in range(n):
		if a[i] <= x:
			continue
		ans += b[i]
	if ans <= x:
		return 1
	return 0

def bsearch(l, r):
	m = (l + r) // 2
	if f(m):
		if f(m - 1) == 0:
			return m
		return bsearch(l, m - 1)
	return bsearch(m + 1, r)
t = int(input())
for you in range(t):
	n = int(input())
	l = input().split()
	a = [int(i) for i in l]
	l = input().split()
	b = [int(i) for i in l]
	print(bsearch(0, 10 ** 9 + 5))


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 32, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
for ik in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l1 = list(map(int, input().split()))

	def find(x):
		ans = 0
		for i in range(n):
			if l[i] > x:
				ans += l1[i]
		if ans <= x:
			return True
		return False
	st = 0
	end = max(l)
	ans = end
	while st <= end:
		mid = (st + end) // 2
		if find(mid) == True:
			ans = mid
			end = mid - 1
		else:
			st = mid + 1
	print(ans)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def gift():
	for _ in range(t):
		n = int(input())
		an = list(map(int, input().split()))
		bn = list(map(int, input().split()))
		left = []
		maxTime = 0
		timeSpend = 0
		for i in range(n):
			if an[i] <= bn[i]:
				maxTime = max(an[i], maxTime)
			else:
				left.append([an[i], bn[i]])
		fleft = []
		for ele in left:
			if ele[0] > maxTime:
				fleft.append(ele)
		fleft.sort(key=lambda x: (-x[0], -x[1]))
		for ele in fleft:
			(ani, bni) = ele
			if bni + timeSpend < ani:
				timeSpend += bni
				maxTime = max(maxTime, timeSpend)
			else:
				maxTime = max(ani, maxTime)
		yield maxTime
t = int(input())
ans = gift()
print(*ans, sep='\n')


import sys
from collections import *
input = sys.stdin.readline
t = int(input())
while t:
	t -= 1
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	c = [0] * n
	for i in range(n):
		c[i] = (a[i], b[i])
	c.sort(key=lambda x: x[0], reverse=True)
	res = sum(b)
	j = 0
	for i in range(n):
		res = min(res, max(c[i][0], j))
		j += c[i][1]
	print(res)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	ab = []
	for i in range(n):
		ab.append([a[i], b[i]])
	ab.sort(key=lambda x: x[0], reverse=True)
	bPrefSum = [0 for _ in range(n)]
	for i in range(n):
		bPrefSum[i] = ab[i][1]
		if i > 0:
			bPrefSum[i] += bPrefSum[i - 1]
	aMaxFromRight = [0 for _ in range(n)]
	for i in range(n - 1, -1, -1):
		aMaxFromRight[i] = ab[i][0]
		if i < n - 1:
			aMaxFromRight[i] = max(aMaxFromRight[i], aMaxFromRight[i + 1])
	ans = float('inf')
	for i in range(-1, n):
		if i == -1:
			bTot = 0
		else:
			bTot = bPrefSum[i]
		if i + 1 == n:
			aTot = 0
		else:
			aTot = aMaxFromRight[i + 1]
		ans = min(ans, max(aTot, bTot))
	print(ans)


from math import *
import threading
import sys
mod = 10 ** 9 + 7

def npr(n, r):
	return factorial(n) // factorial(n - r) if n >= r else 0

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = -1
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = mid
			break
	return ans

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum

def graph(n, m):
	adj = dict()
	for i in range(1, n + 1):
		adj.setdefault(i, 0)
	for i in range(m):
		(a, b) = map(int, input().split())
		adj[a] += 1
		adj[b] += 1
	return adj

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	li = []
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, len(prime)):
		if prime[p]:
			li.append(p)
	return li

def primefactors(n):
	factors = []
	while n % 2 == 0:
		factors.append(2)
		n //= 2
	for i in range(3, int(sqrt(n)) + 1, 2):
		while n % i == 0:
			factors.append(i)
			n //= i
	if n > 2:
		factors.append(n)
	return factors

def prod(li):
	ans = 1
	for i in li:
		ans *= i
	return ans
sys.setrecursionlimit(300000)
for _ in range(int(input()) if True else 1):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	suf = [sum(b)]
	dish = []
	for i in range(n):
		dish.append((a[i], b[i]))
	dish.sort()
	for i in range(n):
		suf.append(suf[-1] - dish[i][1])
	ans = [sum(b)]
	for i in range(n):
		ans.append(max(dish[i][0], suf[i + 1]))
	print(min(ans))


def f():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ab = [[a[i], b[i]] for i in range(n)]
	ab.sort(reverse=True)
	minn = -1
	summ = 0
	for i in range(n):
		cur_min = max(ab[i][0], summ)
		if minn == -1 or cur_min < minn:
			minn = cur_min
		summ += ab[i][1]
	print(min(minn, summ))
t = int(input())
for i in range(t):
	f()


noOfTestCases = int(input())
for testCase in range(noOfTestCases):
	noOfDeliveries = int(input())
	As = [int(i) for i in input().split()]
	Bs = [int(i) for i in input().split()]
	tempIndex = list(range(len(As)))
	tempIndex.sort(key=As.__getitem__, reverse=True)
	As = list(map(As.__getitem__, tempIndex))
	Bs = list(map(Bs.__getitem__, tempIndex))
	Btime = Bs[0]
	totalTime = As[0]
	for i in range(1, noOfDeliveries):
		totalTime = min(totalTime, max(As[i], Btime))
		Btime += Bs[i]
	totalTime = min(totalTime, Btime)
	print(totalTime)


def solve(n, a, b):
	c = list(zip(a, b))
	c = sorted(c, reverse=True)
	prev = c[0][0]
	cumsum = 0
	best = c[0][0]
	for tup in c:
		if tup[0] != prev:
			cont = max(tup[0], cumsum)
			if cont < best:
				best = cont
		cumsum += tup[1]
		prev = tup[0]
	best = min(best, cumsum)
	print(best)
t = int(input())
for j in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	solve(n, a, b)


import os
import sys
from io import BytesIO, IOBase
import math

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n / i
	if n > 2:
		l.append(int(n))
	return l

def isPrime(n):
	if n == 1:
		return False
	else:
		root = int(n ** 0.5)
		root += 1
		for i in range(2, root):
			if n % i == 0:
				return False
		return True

def maxPrimeFactors(n):
	maxPrime = -1
	while n % 2 == 0:
		maxPrime = 2
		n >>= 1
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			maxPrime = i
			n = n / i
	if n > 2:
		maxPrime = n
	return int(maxPrime)

def countcon(s, i):
	c = 0
	ch = s[i]
	for i in range(i, len(s)):
		if s[i] == ch:
			c += 1
		else:
			break
	return c
for xyz in range(0, int(input())):
	n = int(input())
	l = [[0, 0] for i in range(0, n)]
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(0, n):
		l[i] = [a[i], b[i]]
	tbs = 0
	l.sort(reverse=True)
	ind = 0
	ans = 0
	for i in range(0, n):
		l[i][0] = max(0, l[i][0] - tbs)
		if l[i][0] > l[i][1]:
			tbs += l[i][1]
			ans += l[i][1]
		else:
			ans += l[i][0]
			tbs += l[i][0]
	print(ans)


t = int(input())
ans = []
for i in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	if n == 1:
		ans.append(min(a[0], b[0]))
	else:
		w = []
		for i in range(n):
			w.append([a[i], b[i]])
		w.sort()
		w.reverse()
		w.insert(0, [0, 0])
		w.append([0, 0])
		l = []
		l1 = []
		for i in range(1, len(w)):
			if w[i][0] != w[i - 1][0]:
				l.append(l1)
				l1 = [w[i]]
			else:
				l1.append(w[i])
		l.pop(0)
		l.append([[0, 0]])
		p = 0
		for i in range(len(l)):
			z = 0
			for o in range(len(l[i])):
				z += l[i][o][1]
			if l[i][0][0] <= p + z:
				ans.append(l[i][0][0])
				break
			elif l[i + 1][0][0] <= p + z:
				ans.append(p + z)
				break
			else:
				p += z
for i in ans:
	print(i)


import math, sys
from collections import defaultdict, Counter, deque
from functools import reduce
INF = float('inf')
MOD = int(1000000000.0) + 7

def solve():
	n = int(input())
	a = array()
	b = array()
	arr = sorted(zip(a, b), reverse=True)
	ans = arr[0][0]
	person = 0
	for i in range(n):
		ans = max(arr[i][0], person)
		if arr[i][0] > person + arr[i][1]:
			person += arr[i][1]
		else:
			break
	else:
		print(person)
		return
	print(ans)
	return

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()

def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a

def input():
	return sys.stdin.readline().rstrip('\n').strip()

def print(*args, sep=' ', end='\n'):
	first = True
	for arg in args:
		if not first:
			sys.stdout.write(str(sep))
		sys.stdout.write(str(arg))
		first = False
	sys.stdout.write(end)

def vars():
	return map(int, input().split())

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


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict as dd, deque as dq
import math, string

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
MOD = 10 ** 9 + 7

def solve():
	N = getInt()
	(A, B) = (getInts(), getInts())
	C = list(zip(A, B))
	C.sort()
	B_prefs = [0]
	curr = 0
	for (a, b) in C:
		curr += b
		B_prefs.append(curr)
	best = 10 ** 18
	for j in range(N + 1):
		tmp = 10 ** 18
		if j > 0:
			tmp = C[j - 1][0]
		else:
			tmp = 0
		tmp = max(B_prefs[-1] - B_prefs[j], tmp)
		best = min(tmp, best)
	return best
for _ in range(getInt()):
	print(solve())


from sys import stdout, stdin
for _ in range(int(input())):
	n = int(stdin.readline())
	l = list(map(int, stdin.readline().split()))
	a = list(map(int, stdin.readline().split()))
	l = [[l[i], a[i]] for i in range(n)]
	l.sort(key=lambda x: x[0], reverse=True)
	c = 0
	f = 0
	for i in l:
		if i[0] < i[1]:
			c = max(i[0], c)
			break
		elif i[0] >= i[1]:
			if c + i[1] <= i[0]:
				c = c + i[1]
			else:
				c = max(i[0], c)
				break
	stdout.write('{0}\n'.format(c))


t = int(input())
for j in range(t):
	r = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = sorted([(a[i], b[i]) for i in range(len(a))])[::-1]
	cost = 0
	cour = 0
	for i in range(len(c)):
		if cost + c[i][1] > c[i][0]:
			cour = c[i][0]
			break
		else:
			cost += c[i][1]
	print(max(cost, cour))


t = int(input())
for j in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	f = list(map(int, input().split()))
	s = sum(f)
	f = [x for (_, x) in sorted(zip(l, f))]
	l.sort()
	ans = min(l[-1], s)
	cur = 0
	for j in range(n):
		cur += f[j]
		ans = min(ans, max(l[j], s - cur))
	print(ans)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	ab = []
	for (x, y) in zip(a, b):
		ab.append([x, y])
	ab.sort()
	ab.reverse()
	ps = [ab[0][1]]
	for (x, y) in ab[1:]:
		ps.append(ps[-1] + y)
	res = ab[0][0]
	for x in range(1, n):
		t = max(ps[x - 1], ab[x][0])
		if t < res:
			res = t
	print(min(res, ps[-1]))


lis = []
a = []
for i in range(int(input())):
	n = int(input())
	time = 0
	temp = 0
	templis = list(map(int, input().split()))
	templist = list(map(int, input().split()))
	lis = list(zip(templis, templist))
	lis.sort(reverse=True)
	for (j, k) in lis:
		if temp + k < j:
			time = max(time, temp + k)
			temp += k
		elif j > time:
			time = j
	a.append(time)
for i in a:
	print(i)


import sys
n = int(input())
for i in range(n):
	m = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	b = list(map(int, sys.stdin.readline().split()))
	c = sorted(list(zip(a, b)), reverse=True)
	d = 0
	for i in range(m):
		d += c[i][1]
		if d >= c[i][0]:
			d = max(c[i][0], d - c[i][1])
			break
	sys.stdout.write('{}\n'.format(d))


import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
from decimal import *
BUFSIZE = 8192
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		pairs = sorted([(a[i], b[i]) for i in range(n)], key=lambda x: x[0], reverse=True)
		s = 0
		ans = min(sum(b), max(a))
		for p in pairs:
			cur = max(s, p[0])
			s += p[1]
			ans = min(ans, cur)
		print(ans)
main()


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	res = []
	for j in range(n):
		res.append([a[j], b[j]])
	res.sort()
	pre = [0]
	for j in range(n):
		pre.append(pre[-1] + res[j][1])
	s = pre[-1]
	j = 0
	ans = float('inf')
	while j < n:
		ans = min(ans, max(res[j][0], s - pre[j + 1]))
		j += 1
	print(min(s, ans))


def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
n = inp()
for _ in range(n):
	x = inp()
	a = inlt()
	b = inlt()
	c = [list(x) for x in zip(a, b)]
	c.sort(key=lambda x: x[0])
	time = 0
	res = 0
	for i in range(x - 1, -1, -1):
		if c[i][0] > time + c[i][1]:
			time += c[i][1]
		else:
			res = max(c[i][0], time)
			break
	if res == 0:
		print(time)
	else:
		print(res)


import sys

def get_input():
	return sys.stdin.readline()
for _ in range(int(get_input())):
	n = int(get_input())
	dishes = sorted(zip(map(int, get_input().split()), map(int, get_input().split())))
	walktime = sum([dish[1] for dish in dishes])
	best = walktime
	for i in range(n):
		walktime -= dishes[i][1]
		best = min(best, max(walktime, dishes[i][0]))
	print(best)


from sys import stdin, stdout

def make_attempt(courierTimes, petyaTimes):
	pairsSortedByCourierTime = list(sorted(zip(courierTimes, petyaTimes), key=lambda x: x[0]))
	condensed = {0: 0}
	for (i, j) in pairsSortedByCourierTime:
		if i not in condensed:
			condensed[i] = 0
		condensed[i] += j
	oldPetyaTime = 0
	for i in reversed(sorted(condensed.keys())):
		oldDeliveryTime = i
		oldArrivalTime = max(oldPetyaTime, oldDeliveryTime)
		newPickupSpot = condensed[i]
		newPetyaTime = oldPetyaTime + newPickupSpot
		newDeliveryTime = pairsSortedByCourierTime[-1][0]
		newArrivalTime = max(newPetyaTime, oldDeliveryTime)
		if oldArrivalTime < newArrivalTime:
			break
		oldPetyaTime = newPetyaTime
		oldArrivalTime = newArrivalTime
	return oldArrivalTime

def test_solver():
	n = 4
	courierTimes = [3, 7, 4, 5]
	petyaTimes = [2, 1, 2, 4]
	print(make_attempt(courierTimes, petyaTimes))

def main():
	t = int(stdin.readline())
	for i in range(t):
		n = int(stdin.readline())
		courierTimes = [int(i) for i in stdin.readline().split()]
		petyaTimes = [int(i) for i in stdin.readline().split()]
		stdout.write('%d\n' % make_attempt(courierTimes, petyaTimes))
main()


import sys
input = sys.stdin.readline
ri = lambda : int(input())
rl = lambda : list(map(int, input().split()))
rs = lambda : input()
for _ in range(ri()):
	n = ri()
	c = rl()
	v = rl()
	temp = list(zip(c, v))
	temp.sort(reverse=True)
	(a, b) = (0, 0)
	ans = 0
	for i in range(n):
		if max(max(a, temp[i][0]), b) <= max(a, b + temp[i][1]):
			a = max(a, temp[i][0])
		else:
			b += temp[i][1]
	ans = max(a, b)
	print('%d' % ans)


def abc(n, a, b, i, x, y):
	if i == n:
		return max(x, y)
	return min(abc(n, a, b, i + 1, x + b[i], y), abc(n, a, b, i + 1, x, max(y, a[i])))
t = int(input())
import random
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = []
	for i in range(n):
		l.append([a[i], b[i]])
	l.sort(reverse=True)
	c = 0
	ans = 0
	for i in l:
		if c + i[1] < i[0]:
			c += i[1]
			ans = max(ans, c)
		else:
			ans = max(ans, i[0])
	print(ans)


from sys import stdin, stdout
from collections import deque
import bisect
R = lambda : stdin.readline().strip()
RL = lambda f=None: list(map(f, R().split(' '))) if f else list(R().split(' '))
output = lambda x: stdout.write(str(x) + '\n')
output_list = lambda x: output(' '.join(map(str, x)))

def sorted_enumerate(seq):
	return [i for (v, i) in sorted(((v, i) for (i, v) in enumerate(seq)))]
T = int(input())
for _ in range(T):
	n = int(input())
	a = RL(int)
	b = RL(int)
	args = sorted_enumerate(a)
	pick = 0
	deli = max(a)
	ma = max(pick, deli)
	for i in range(n - 1, -1, -1):
		pick += b[args[i]]
		if i == 0:
			deli = 0
		else:
			deli = a[args[i - 1]]
		cur_ma = max(pick, deli)
		if cur_ma < ma:
			ma = cur_ma
	print(ma)


from sys import stdin, stdout
from math import gcd, sqrt, factorial, pi, inf
from collections import deque, defaultdict
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(str(x) + '\n')
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
for _ in range(I()):
	n = I()
	a = sorted(zip(R(), R()), key=lambda x: x[0])
	ans = sum([i[1] for i in a])
	p = ans
	for i in a:
		p -= i[1]
		ans = min(ans, max(p, i[0]))
	print(ans)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
from heapq import *
from math import gcd, factorial, floor, ceil, sqrt
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for pp in range(t):
		solve(pp)

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def google(p):
	print('Case #' + str(p) + ': ', end='')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(x, y, p):
	y %= p - 1
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
inf = pow(10, 20)
mod = 10 ** 9 + 7

def bucketsort(order, seq):
	buckets = [0] * (max(seq) + 1)
	for x in seq:
		buckets[x] += 1
	for i in range(len(buckets) - 1):
		buckets[i + 1] += buckets[i]
	new_order = [-1] * len(seq)
	for i in reversed(order):
		x = seq[i]
		idx = buckets[x] = buckets[x] - 1
		new_order[idx] = i
	return new_order

def ordersort(order, seq, reverse=False):
	bit = max(seq).bit_length() >> 1
	mask = (1 << bit) - 1
	order = bucketsort(order, [x & mask for x in seq])
	order = bucketsort(order, [x >> bit for x in seq])
	if reverse:
		order.reverse()
	return order

def long_ordersort(order, seq):
	order = ordersort(order, [int(i & 2147483647) for i in seq])
	return ordersort(order, [int(i >> 31) for i in seq])

def multikey_ordersort(order, *seqs, sort=ordersort):
	for i in reversed(range(len(seqs))):
		order = sort(order, seqs[i])
	return order

def solve(case):
	n = int(inp())
	a = [0] + lis()
	b = [0] + lis()
	order = multikey_ordersort(range(n + 1), a, b)
	sl = []
	for i in order:
		sl.append((a[i], b[i]))
	sl = sl[::-1]
	curr = 0
	ans = inf
	for i in range(n + 1):
		ans = min(ans, max(sl[i][0], curr))
		curr += sl[i][1]
	print(ans)
testcase(int(inp()))


import sys

def get_ints():
	return list(map(int, sys.stdin.readline().strip().split()))
t = int(sys.stdin.readline())
for _ in range(t):
	n = int(sys.stdin.readline())
	a = get_ints()
	b = get_ints()
	l = []
	for i in range(n):
		l.append([a[i], b[i]])
	l.sort()
	(ans, c, f) = (0, 0, 0)
	for i in range(n - 1, -1, -1):
		if c >= l[i][0]:
			ans = c
			f = 1
			break
		elif c + l[i][1] >= l[i][0]:
			ans = l[i][0]
			f = 1
			break
		else:
			c = c + l[i][1]
	if f == 0:
		ans = c
	sys.stdout.write(str(ans) + '\n')


test = int(input())
while test > 0:
	test -= 1
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	if sum(b) <= min(a):
		print(sum(b))
		continue
	arr = []
	for i in range(len(a)):
		arr.append([a[i], b[i]])
	arr.sort(key=lambda x: x[0])
	s = sum(b)
	ans = float('inf')
	for i in range(len(arr)):
		temp = s - arr[i][1]
		ans = min(max(temp, arr[i][0]), ans)
		s -= arr[i][1]
	print(ans)


from sys import stdin, stdout
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	b = list(map(int, stdin.readline().split()))
	mini = 0
	di = {}
	for i in range(len(a)):
		if a[i] in di:
			di[a[i]].append(b[i])
		else:
			di[a[i]] = [b[i]]
		if a[i] > mini:
			mini = a[i]
	psum = sum(di[mini])
	k = sorted(di.keys(), reverse=True)
	k.append(0)
	i = 1
	mini = min(mini, max(k[1], psum))
	counter = 0
	while i < len(k) - 1:
		psum += sum(di[k[i]])
		if psum < k[i]:
			if psum < k[i + 1]:
				mini = k[i + 1]
			else:
				mini = psum
				counter = 1
				break
		if counter == 1:
			break
		i += 1
	print(min(mini, psum))


import sys, os.path
from collections import *
from heapq import *
from copy import *
import math
mod = 10 ** 9 + 7
read = lambda : map(int, input().split())
inf = float('inf')
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
for t in range(int(input())):
	n = int(input())
	a = list(read())
	b = list(read())
	s = sum(b)
	temp = 0
	pair = []
	k = 0
	for i in range(n):
		x = [a[i], b[i]]
		pair.append(x)
	pair.sort(reverse=True)
	k = 0
	for i in range(n):
		pair[i][1] += k
		k = pair[i][1]
	best = 0
	best = pair[0][0]
	for i in range(1, n):
		best = min(best, max(pair[i][0], pair[i - 1][1]))
	best1 = pair[0][1]
	if n > 1:
		if pair[0][1] >= pair[1][0] and pair[0][0] > pair[0][1]:
			best = pair[0][1]
	best1 = 0
	if s <= pair[0][0]:
		best1 = s
	if best1:
		print(min(best, best1))
	else:
		print(best)


import sys
input = sys.stdin.readline
output = []
for _ in range(int(input())):
	n = int(input())
	a = map(int, input().split())
	b = map(int, input().split())
	costs = list(zip(a, b))
	costs.sort(key=lambda x: x[0], reverse=True)
	petya = 0
	for i in range(n):
		if petya + costs[i][1] < costs[i][0]:
			petya += costs[i][1]
		else:
			petya = max(petya, costs[i][0])
			break
	print(petya)


from collections import deque, defaultdict

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	new = []
	for i in range(n):
		new.append((a[i], b[i]))
	new.sort(key=lambda x: x[0])
	pre = [0]
	for i in range(n):
		pre.append(pre[-1] + new[i][1])
	ans = pre[-1]
	ma = 0
	for i in range(n):
		ma = max(ma, new[i][0])
		s = pre[-1] - pre[i + 1]
		ans = min(ans, max(ma, s))
	print(ans)

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()
main()


def f(aa, bb, target):
	total = 0
	for i in range(len(aa)):
		if aa[i] > target:
			total += bb[i]
	return total <= target
t = int(input())
for case in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	low = 1
	high = 1000000000
	while low < high:
		mid = (low + high) // 2
		res = f(a, b, mid)
		if res:
			high = mid
		else:
			low = mid + 1
	print(low)


from sys import stdin, stdout
from math import inf

def main():
	for _ in range(int(stdin.readline())):
		n = int(stdin.readline())
		a = list(map(int, stdin.readline().split()))
		b = list(map(int, stdin.readline().split()))
		tmp = [(x, y) for (x, y) in zip(a, b)]
		tmp.sort(key=lambda x: x[0])
		ans = inf
		suffix = 0
		for i in range(n - 1, -1, -1):
			ans = min(ans, max(tmp[i][0], suffix))
			suffix += tmp[i][1]
		if suffix < ans:
			ans = suffix
		stdout.write('%d\n' % ans)
main()


import sys
input = sys.stdin.buffer.readline
ri = lambda : int(input())
rl = lambda : list(map(int, input().split()))
rs = lambda : input().decode().rstrip('\n\r')
wrt = sys.stdout.write
pr = lambda *args, end='\n': wrt(' '.join([str(x) for x in args]) + end)
xrange = lambda args: reversed(range(args))
cdiv = lambda x, y: -(-x // y)
enum = enumerate
inf = float('inf')
mod = 10 ** 9 + 7
Cases = ri()
for Case in range(Cases):
	n = ri()
	a = rl()
	b = rl()
	ar = [(i, j) for (i, j) in zip(a, b)]
	ar.sort(key=lambda x: x[0])
	tmax = 0
	tsum = sum(b)
	i = 0
	ans = inf
	while i <= n - 1:
		ans = min(ans, max(tsum, tmax))
		tmax = max(tmax, ar[i][0])
		tsum -= ar[i][1]
		i += 1
		ans = min(ans, max(tsum, tmax))
	pr(ans)


import sys
input = sys.stdin.readline

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
t = inp()
for _ in range(t):
	n = inp()
	a = inara()
	b = inara()
	hi = max(a)
	lo = 1
	ans = hi
	while hi >= lo:
		mid = (hi + lo) // 2
		lagbe = 0
		for i in range(n):
			if a[i] > mid:
				lagbe += b[i]
		if lagbe <= mid:
			ans = mid
			hi = mid - 1
		else:
			lo = mid + 1
	print(ans)


import sys
(*data,) = map(int, sys.stdin.read().split()[::-1])

def inp():
	return data.pop()

def solve(delivery, takeaway):
	hi = sum(delivery)
	lo = 0
	while lo < hi:
		mid = (lo + hi) // 2
		s = 0
		for (i, t) in enumerate(delivery):
			if t > mid:
				s += takeaway[i]
		if s > mid:
			lo = mid + 1
		else:
			hi = mid
	return lo
ans = []
for _ in range(inp()):
	n = inp()
	(*delivery,) = [inp() for _ in range(n)]
	(*takeaway,) = [inp() for _ in range(n)]
	ans.append(solve(delivery, takeaway))
print('\n'.join(map(str, ans)))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	dp = []
	c = sorted(a)
	summ = 0
	for i in range(n):
		dp.append([a[i], i])
		summ += b[i]
	dp.sort()
	k = n - 1
	ans = max(a)
	count = 0
	for i in dp[-1::-1]:
		k -= 1
		count += b[i[1]]
		ans = min(ans, max(count, c[k]))
	print(min(ans, summ))


T = int(input())
for z in range(T):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	c = list(zip(a, b))
	c.sort(reverse=True)
	small = 10 ** 9
	rem = 0
	for i in range(n + 1):
		if i != n:
			e = c[i][0]
		else:
			e = 0
		if i != 0:
			rem += c[i - 1][1]
		e = max(e, rem)
		if small > e:
			small = e
	print(small)


import bisect
import math

def solve(a, b, n):
	both = []
	for j in range(n):
		both.append([a[j], b[j]])
	both.sort(reverse=True)
	time = [both[0][1]]
	for z in range(1, n):
		time.append(time[-1] + both[z][1])
	probable_ans = [both[0][0]]
	for j in range(1, n):
		probable_ans.append(max(time[j - 1], both[j][0]))
	probable_ans.append(time[-1])
	return min(probable_ans)
t = int(input())
ans = []
for i in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	ans.append(solve(a, b, n))
for test in ans:
	print(test)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	n += 2
	a = [0] + list(map(int, input().split())) + [10 ** 18]
	b = [10 ** 18] + list(map(int, input().split())) + [0]
	ab = [[a[i], b[i]] for i in range(n)]
	ab = sorted(ab, key=lambda x: x[0])
	acum = [0]
	for i in range(n - 2, -1, -1):
		acum.append(acum[-1] + ab[i][1])
	acum = acum[::-1]
	ans = 10 ** 18
	for i in range(n - 1):
		ans = min(ans, max(ab[i][0], acum[i + 1]))
	print(ans)


import sys
import math
from collections import defaultdict, deque
input = sys.stdin.readline

def inar():
	return [int(el) for el in input().split()]

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = inar()
		b = inar()
		tup = []
		for i in range(n):
			tup.append([a[i], b[i]])
		tup = sorted(tup, key=lambda x: (x[0], x[1]))
		ans1 = 0
		temp = 0
		for i in range(n):
			if tup[i][0] <= tup[i][1] + temp:
				ans1 = max(ans1, tup[i][0])
			else:
				temp += tup[i][1]
				ans1 = max(ans1, temp)
		ans = 0
		temp = 0
		tup = sorted(tup, key=lambda x: (-x[0], x[1]))
		for i in range(n):
			if tup[i][0] <= tup[i][1] + temp:
				ans = max(ans, tup[i][0])
			else:
				temp += tup[i][1]
				ans = max(ans, temp)
		print(min(ans1, ans))
main()


from sys import stdin
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	b = list(map(int, stdin.readline().split()))
	l = []
	for (ind, val) in enumerate(a):
		l.append((val, b[ind]))
	l.sort(reverse=True)
	maxi = l[0][0]
	(i, s) = (0, 0)
	while i < n and s < maxi:
		s += l[i][1]
		maxi = min(maxi, l[i][0])
		i += 1
	if s > maxi:
		i -= 1
		s -= l[i][1]
	print([max(maxi, s), s][i == n])