Polycarp often uses his smartphone. He has already installed $n$ applications on it. Application with number $i$ takes up $a_i$ units of memory.

Polycarp wants to free at least $m$ units of memory (by removing some applications).

Of course, some applications are more important to Polycarp than others. He came up with the following scoring system — he assigned an integer $b_i$ to each application:

$b_i = 1$ — regular application;

$b_i = 2$ — important application.

According to this rating system, his phone has $b_1 + b_2 + \ldots + b_n$ convenience points.

Polycarp believes that if he removes applications with numbers $i_1, i_2, \ldots, i_k$, then he will free $a_{i_1} + a_{i_2} + \ldots + a_{i_k}$ units of memory and lose $b_{i_1} + b_{i_2} + \ldots + b_{i_k}$ convenience points.

For example, if $n=5$, $m=7$, $a=[5, 3, 2, 1, 4]$, $b=[2, 1, 1, 2, 1]$, then Polycarp can uninstall the following application sets (not all options are listed below):

applications with numbers $1, 4$ and $5$. In this case, it will free $a_1+a_4+a_5=10$ units of memory and lose $b_1+b_4+b_5=5$ convenience points;

applications with numbers $1$ and $3$. In this case, it will free $a_1+a_3=7$ units of memory and lose $b_1+b_3=3$ convenience points.

applications with numbers $2$ and $5$. In this case, it will free $a_2+a_5=7$ memory units and lose $b_2+b_5=2$ convenience points.

Help Polycarp, choose a set of applications, such that if removing them will free at least $m$ units of memory and lose the minimum number of convenience points, or indicate that such a set does not exist.


-----Input-----

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

The first line of each test case contains two integers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5$, $1 \le m \le 10^9$) — the number of applications on Polycarp's phone and the number of memory units to be freed.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$) — the number of memory units used by applications.

The third line of each test case contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le 2$) — the convenience points of each application.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.


-----Output-----

For each test case, output on a separate line:

-1, if there is no set of applications, removing which will free at least $m$ units of memory;

the minimum number of convenience points that Polycarp will lose if such a set exists.


-----Examples-----

Input
5
5 7
5 3 2 1 4
2 1 1 2 1
1 3
2
1
5 10
2 3 2 3 2
1 2 1 2 1
4 10
5 1 3 4
1 2 1 2
4 5
3 2 1 2
2 1 2 1
Output
2
-1
6
4
3


-----Note-----

In the first test case, it is optimal to remove applications with numbers $2$ and $5$, freeing $7$ units of memory. $b_2+b_5=2$.

In the second test case, by removing the only application, Polycarp will be able to clear only $2$ of memory units out of the $3$ needed.

In the third test case, it is optimal to remove applications with numbers $1$, $2$, $3$ and $4$, freeing $10$ units of memory. $b_1+b_2+b_3+b_4=6$.

In the fourth test case, it is optimal to remove applications with numbers $1$, $3$ and $4$, freeing $12$ units of memory. $b_1+b_3+b_4=4$.

In the fifth test case, it is optimal to remove applications with numbers $1$ and $2$, freeing $5$ units of memory. $b_1+b_2=3$.

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Dynamic programming

Sorting

Amortized analysis


Solutions:
__version__ = '2.1'
__date__ = '2021-03-16'
import sys
from bisect import bisect_left
from itertools import accumulate
from math import inf

def solve(n, m, a, b):
	if sum(a) < m:
		return -1
	b1 = list()
	b2 = list()
	for i in range(n):
		if b[i] == 1:
			b1.append(a[i])
		else:
			b2.append(a[i])
	p1 = [0] + list(accumulate(sorted(b1, reverse=True)))
	p2 = [0] + list(accumulate(sorted(b2, reverse=True)))
	answer = inf
	for j in range(len(p1)):
		k = bisect_left(p2, m - p1[j])
		if k < len(p2):
			answer = min(j + 2 * k, answer)
		if p1[j] > m:
			return answer
	return answer

def main(argv=None):
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		print(solve(n, m, a, b))
	return 0
STATUS = main()
sys.exit(STATUS)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	release = [int(i) for i in input().split()]
	cost = [int(i) for i in input().split()]
	one_cost = [release[i] for i in range(n) if cost[i] == 1]
	two_cost = [release[i] for i in range(n) if cost[i] == 2]
	one_cost.sort(reverse=True)
	two_cost.sort(reverse=True)
	one_index = 0
	two_index = 0
	cur = 0
	ans = 0
	while True:
		if cur >= m:
			break
		if two_index >= len(two_cost) and one_index >= len(one_cost):
			break
		if two_index >= len(two_cost):
			cur += one_cost[one_index]
			ans += 1
			one_index += 1
		elif one_index >= len(one_cost):
			cur += two_cost[two_index]
			ans += 2
			two_index += 1
		elif one_cost[one_index] >= two_cost[two_index] or cur + one_cost[one_index] >= m:
			cur += one_cost[one_index]
			ans += 1
			one_index += 1
		elif one_index + 1 < len(one_cost) and one_cost[one_index] + one_cost[one_index + 1] >= two_cost[two_index]:
			cur += one_cost[one_index]
			ans += 1
			one_index += 1
		else:
			cur += two_cost[two_index]
			ans += 2
			two_index += 1
	print(ans if cur >= m else -1)


import sys
from collections import defaultdict, deque
from bisect import bisect_left
input = lambda : sys.stdin.readline().rstrip()
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [*map(int, input().split())]
	b = [*map(int, input().split())]
	(c, d) = ([], [])
	sm = 0
	for i in range(n):
		sm += a[i]
		if b[i] == 1:
			c.append(a[i])
		else:
			d.append(a[i])
	c.sort(reverse=True)
	d.sort(reverse=True)
	for i in range(1, len(c)):
		c[i] += c[i - 1]
	for i in range(1, len(d)):
		d[i] += d[i - 1]
	if sm >= m:
		ans = len(c) + 2 * len(d)
	else:
		print(-1)
		continue
	for i in range(len(c)):
		if c[i] >= m:
			ans = min(ans, i + 1)
			continue
		idx = bisect_left(d, m - c[i])
		if idx != len(d):
			ans = min(ans, i + 2 * idx + 3)
	for i in range(len(d)):
		if d[i] >= m:
			ans = min(ans, 2 * (i + 1))
			continue
		idx = bisect_left(c, m - d[i])
		if idx != len(c):
			ans = min(ans, 2 * i + idx + 3)
	print(ans)


from sys import stdin, stdout
from collections import defaultdict
import math

def main():
	t = int(stdin.readline())
	for _ in range(t):
		(n, m) = list(map(int, stdin.readline().split()))
		a = list(map(int, stdin.readline().split()))
		b = list(map(int, stdin.readline().split()))
		one = []
		two = []
		for i in range(n):
			if b[i] == 1:
				one.append(a[i])
			else:
				two.append(a[i])
		one.sort(reverse=True)
		two.sort(reverse=True)
		count_one = -1
		sm_i = 0
		min_con = 100000000
		for (i, o) in enumerate(one):
			sm_i += o
			if sm_i >= m:
				count_one = i + 1
				min_con = i + 1
				break
		if count_one == -1:
			count_one = len(one)
		sm_t = 0
		for (i, t) in enumerate(two):
			sm_t += t
			if sm_t + sm_i < m:
				continue
			while sm_t + sm_i >= m and count_one > 0:
				count_one -= 1
				sm_i -= one[count_one]
			if sm_t + sm_i < m:
				sm_i += one[count_one]
				count_one += 1
			min_con = min(min_con, (i + 1) * 2 + count_one)
		if min_con == 100000000:
			min_con = -1
		stdout.write(str(min_con) + '\n')
main()


def main():
	cases = int(input())
	ans_list = []
	for _ in range(cases):
		(n, m) = map(int, input().split(' '))
		mem = list(map(int, input().split(' ')))
		conv = list(map(int, input().split(' ')))
		(two_list, one_list) = ([], [])
		for i in range(n):
			if conv[i] == 1:
				one_list.append(mem[i])
			else:
				two_list.append(mem[i])
		one_list.sort()
		two_list.sort()
		(cur_mem, loss) = (0, 0)
		while cur_mem < m and (one_list or two_list):
			if len(one_list) == 0:
				cur_mem += two_list.pop()
				loss += 2
			elif len(two_list) == 0:
				cur_mem += one_list.pop()
				loss += 1
			elif one_list[-1] + cur_mem >= m:
				cur_mem += one_list.pop()
				loss += 1
			else:
				one_sum = one_list[-1] if len(one_list) == 1 else one_list[-1] + one_list[len(one_list) - 2]
				two_sum = two_list[-1]
				if two_sum > one_sum:
					cur_mem += two_list.pop()
					loss += 2
				else:
					cur_mem += one_list.pop()
					loss += 1
		if cur_mem < m:
			ans_list.append(str(-1))
		else:
			ans_list.append(str(loss))
	print('\n'.join(ans_list))
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')
main()


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')
mod = 10 ** 9 + 7

def lcm(x, y):
	return x * y / gcd(x, y)

def fact(x, mod=mod):
	ans = 1
	for i in range(1, x + 1):
		ans = ans * i % mod
	return ans

def arr2D(n, m, default=0):
	return [[default for j in range(m)] for i in range(n)]

def arr3D(n, m, r, default=0):
	return [[[default for k in range(r)] for j in range(m)] for i in range(n)]

def sortDictV(x):
	return {k: v for (k, v) in sorted(x.items(), key=lambda item: item[1])}

class DSU:

	def __init__(self, length):
		self.length = length
		self.parent = [-1] * self.length

	def getParent(self, node, start):
		if node >= self.length:
			return False
		if self.parent[node] < 0:
			if start != node:
				self.parent[start] = node
			return node
		return self.getParent(self.parent[node], start)

	def union(self, node1, node2):
		parent1 = self.getParent(node1, node1)
		parent2 = self.getParent(node2, node2)
		if parent1 == parent2:
			return False
		elif self.parent[parent1] <= self.parent[parent2]:
			self.parent[parent1] += self.parent[parent2]
			self.parent[parent2] = parent1
		else:
			self.parent[parent2] += self.parent[parent1]
			self.parent[parent1] = parent2
		return True

	def getCount(self, node):
		return -self.parent[self.getParent(node, node)]

def exact(num):
	if abs(num - round(num)) <= 10 ** (-9):
		return round(num)
	return num

def solve(n, m, a, b):
	if sum(a) < m:
		return -1
	ones = []
	twos = []
	for i in range(n):
		if b[i] == 1:
			ones.append(a[i])
		else:
			twos.append(a[i])
	ones = sorted(ones, reverse=True)
	twos = sorted(twos, reverse=True)
	(i, j) = (len(twos) - 1, 0)
	k = 0
	minn = float('inf')
	summ = sum(twos)
	while True:
		if summ >= m:
			minn = min(minn, (i + 1) * 2 + j - k)
			if i == -1:
				summ -= ones[k]
				k += 1
			else:
				summ -= twos[i]
				i -= 1
		else:
			if j == len(ones):
				break
			summ += ones[j]
			j += 1
		if summ >= m:
			minn = min(minn, (i + 1) * 2 + j - k)
	return minn
for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	print(solve(n, m, a, b))


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
from itertools import accumulate
mod = pow(10, 9) + 7
mod2 = 998244353

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

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

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

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

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

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

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(int(inp())):
	(n, m) = mp()
	a = lmp()
	b = lmp()
	t = sum(a)
	if t < m:
		print(-1)
	else:
		(l1, l2) = ([], [])
		for i in range(n):
			if b[i] == 1:
				l1.append(a[i])
			else:
				l2.append(a[i])
		l1.sort(reverse=True)
		l2.sort(reverse=True)
		l1 = [0] + list(accumulate(l1))
		l2 = [0] + list(accumulate(l2))
		(n1, n2) = (len(l1), len(l2))
		ans = inf
		for i in range(n1):
			sm = l1[i]
			rem = m - sm
			x = bl(l2, rem)
			if x == 0:
				ans = min(ans, i)
			elif x == n2:
				continue
			else:
				ans = min(ans, i + 2 * x)
		print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip()
T = int(input())
for _ in range(T):
	(N, M) = map(int, input().split())
	A = [int(a) for a in input().split()]
	B = [int(a) for a in input().split()]
	X = []
	Y = []
	for (a, b) in zip(A, B):
		if b == 1:
			X.append(a)
		else:
			Y.append(a)
	X = [0] + sorted(X, key=lambda x: -x)
	Y = [0] + sorted(Y, key=lambda x: -x)
	for i in range(1, len(X)):
		X[i] += X[i - 1]
	for i in range(1, len(Y)):
		Y[i] += Y[i - 1]
	if X[-1] + Y[-1] < M:
		print(-1)
		continue
	j = len(Y) - 1
	ans = 1 << 50
	for i in range(len(X)):
		while j and X[i] + Y[j - 1] >= M:
			j -= 1
		if X[i] + Y[j] >= M:
			ans = min(ans, i + j * 2)
	print(ans)


import bisect

def solve(mem, points, n, m, ans):
	ones = []
	twos = []
	for i in range(n):
		if points[i] == 1:
			ones.append(mem[i])
		else:
			twos.append(mem[i])
	ones.sort(reverse=True)
	twos.sort(reverse=True)
	for i in range(1, len(ones)):
		ones[i] += ones[i - 1]
	for i in range(1, len(twos)):
		twos[i] += twos[i - 1]
	min_val = float('inf')
	for one in range(len(ones) + 1):
		if one == 0:
			rem = m
		else:
			rem = max(0, m - ones[one - 1])
		if rem == 0:
			min_val = min(min_val, one)
		else:
			index = bisect.bisect(twos, rem - 1)
			if index < len(twos):
				min_val = min(min_val, one + 2 * (index + 1))
	if min_val == float('inf'):
		min_val = -1
	ans.append(str(min_val))

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


import sys, os, io
import math, bisect, operator
(inf, mod) = (float('inf'), 10 ** 9 + 7)
from itertools import groupby, accumulate
from heapq import heapify, heappop, heappush
from collections import deque, Counter, defaultdict
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
Neo = lambda : list(map(int, input().split()))
(test,) = Neo()
for _ in range(test):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	C1 = []
	C2 = []
	for (a, b) in zip(A, B):
		if b == 1:
			C1.append(a)
		else:
			C2.append(a)
	C1.sort(reverse=True)
	C2.sort(reverse=True)
	C1 = [0] + C1
	C2 = [0] + C2
	C1 = list(accumulate(C1))
	C2 = list(accumulate(C2))
	ans = inf
	for i in range(len(C1)):
		s = C1[i]
		p = m - s
		j = bisect.bisect_left(C2, p)
		if j == 0:
			ans = min(ans, i * 1)
		elif j == len(C2):
			continue
		else:
			ans = min(ans, i * 1 + j * 2)
	if ans != inf:
		print(ans)
	else:
		print(-1)


import sys
import heapq
from collections import deque

def primes(n):
	sieve = [True] * n
	for i in range(3, int(n ** 0.5) + 1, 2):
		if sieve[i]:
			sieve[i * i::2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
	return [2] + [i for i in range(3, n, 2) if sieve[i]]

def factor(n, l, d):
	F = False
	for p in l:
		if n % p == 0:
			if p in d:
				d[p] += 1
			else:
				d[p] = 1
			F = True
			break
	if F:
		factor(n // p, l, d)

def find(parent, i):
	if parent[i] != i:
		parent[i] = find(parent, parent[i])
	return parent[i]

def union(parent, rank, xx, yy):
	x = find(parent, xx)
	y = find(parent, yy)
	if rank[x] > rank[y]:
		parent[y] = x
	elif rank[y] > rank[x]:
		parent[x] = y
	else:
		parent[y] = x
		rank[x] += 1
ans = 0
n = int(sys.stdin.readline().strip())
for j in range(n):
	AB = sys.stdin.readline().strip().split()
	a = int(AB[0])
	b = int(AB[1])
	ak = sys.stdin.readline().strip().split()
	bk = sys.stdin.readline().strip().split()
	h1 = []
	h2 = []
	h3 = []
	h4 = []
	ans = 0
	for i in range(a):
		ak[i] = int(ak[i])
		bk[i] = int(bk[i])
		if bk[i] == 1:
			h1.append(ak[i])
		else:
			h2.append(ak[i])
	if sum(h1) + sum(h2) < b:
		print(-1)
		continue
	h1.sort()
	h2.sort()
	bb = b
	while b > 0:
		sa = 0
		sb = 0
		if len(h1) >= 2:
			sa = h1[-1] + h1[-2]
		elif h1:
			sa = h1[-1]
		if h2:
			sb = h2[-1]
		if sb >= sa:
			if h2:
				b -= h2.pop()
				ans += 2
		else:
			if h1:
				b -= h1.pop()
				ans += 1
			if h1:
				b -= h1.pop()
				ans += 1
	for i in range(a):
		if bk[i] == 1:
			h3.append(ak[i])
		else:
			h4.append(ak[i])
	h3.sort()
	h4.sort()
	ans2 = 0
	b = bb
	if h3:
		ans2 += 1
		b -= h3.pop()
		while b > 0:
			sa = 0
			sb = 0
			if len(h3) >= 2:
				sa = h3[-1] + h3[-2]
			elif h3:
				sa = h3[-1]
			if h4:
				sb = h4[-1]
			if sb >= sa:
				b -= h4.pop()
				ans2 += 2
			else:
				if h3:
					b -= h3.pop()
					ans2 += 1
				if h3:
					b -= h3.pop()
					ans2 += 1
		ans = min(ans, ans2)
	print(ans)


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
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())
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
mod = 10 ** 9 + 7
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
	fact(x, mod)
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa.reverse()

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 isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def floorsum(a, b, c, n):
	if a == 0:
		return b // c * (n + 1)
	if a >= c or b >= c:
		return floorsum(a % c, b % c, c, n) + b // c * (n + 1) + a // c * n * (n + 1) // 2
	m = (a * n + b) // c
	return n * m - floorsum(c, c - b - 1, a, m - 1)

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 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
		seen.add(u)
		for (v, w) in graph[u]:
			if v not in d or d[v] > d[u] + w:
				d[v] = d[u] + w
				heappush(heap, (d[v], v))
	return d

def GP(it):
	return [[ch, len(list(g))] for (ch, g) in groupby(it)]

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

def lis(nums):
	res = []
	for k in nums:
		i = bisect.bisect_left(res, k)
		if i == len(res):
			res.append(k)
		else:
			res[i] = k
	return len(res)

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None

def nb(i, j):
	for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j - 1], [i, j + 1]]:
		if 0 <= ni < n and 0 <= nj < m:
			yield (ni, nj)

def topo(n):
	q = deque()
	res = []
	for i in range(1, n + 1):
		if ind[i] == 0:
			q.append(i)
			res.append(i)
	while q:
		u = q.popleft()
		for v in g[u]:
			ind[v] -= 1
			if ind[v] == 0:
				q.append(v)
				res.append(v)
	return res

@bootstrap
def gdfs(r, p):
	if len(g[r]) == 1 and p != -1:
		yield None
	for ch in g[r]:
		if ch != p:
			yield gdfs(ch, r)
	yield None

def f(x):
	d[a[-1]] -= 1
	d[a[x]] -= 1
	res.append([a[-1], a[x]])
	last = a[-1]
	for i in range(2 * n - 2, -1, -1):
		if d[a[i]] > 0:
			d[a[i]] -= 1
			if d[last - a[i]] > 0:
				d[last - a[i]] -= 1
				res.append([a[i], last - a[i]])
				last = a[i]
			else:
				return False
	return True

def f(arr):
	(x, y) = arr[-1]
	if len(op) == 1:
		if op[0] == 1:
			arr.append([y, -x])
		else:
			arr.append([-y, x])
	else:
		p = op[1]
		if op[0] == 3:
			arr.append([2 * p - x, y])
		else:
			arr.append([x, 2 * p - y])
t = N()
for i in range(t):
	(n, m) = RL()
	a = RLL()
	b = RLL()
	if sum(a) < m:
		print(-1)
		continue
	c = []
	d = []
	for (u, v) in zip(a, b):
		if v == 1:
			c.append(u)
		else:
			d.append(u)
	c.sort()
	d.sort()
	(n1, n2) = (len(c), len(d))
	ans = inf
	cur = 0
	for i in range(n1 - 1, -1, -1):
		cur += c[i]
		if cur >= m:
			break
	if cur >= m:
		ans = n1 - i
		j = n2
		while i < n1 and j >= 0:
			cur -= c[i]
			i += 1
			while cur < m:
				j -= 1
				if j < 0:
					break
				cur += d[j]
			if cur >= m:
				ans = min(ans, n1 - i + 2 * (n2 - j))
	else:
		for j in range(n2 - 1, -1, -1):
			cur += d[j]
			if cur >= m:
				break
		ans = n1 + (n2 - j) * 2
		while i < n1 and j >= 0:
			cur -= c[i]
			i += 1
			while cur < m:
				j -= 1
				if j < 0:
					break
				cur += d[j]
			if cur >= m:
				ans = min(ans, n1 - i + 2 * (n2 - j))
	print(ans)


from bisect import *
from sys import *
input = stdin.readline

def indx(val, lis, leng):
	if val <= 0:
		return 0
	if leng == 0:
		return 10 ** 18
	idx = min(bisect_left(lis, val), leng - 1)
	if lis[idx] >= val:
		return idx + 1
	return 10 ** 18
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	if sum(a) < m:
		print(-1)
		continue
	(ones, twos) = ([], [])
	for i in range(n):
		if b[i] == 1:
			ones.append(a[i])
		else:
			twos.append(a[i])
	ones.sort(reverse=True)
	twos.sort(reverse=True)
	(len1, len2) = (len(ones), len(twos))
	for i in range(1, len1):
		ones[i] += ones[i - 1]
	for i in range(1, len2):
		twos[i] += twos[i - 1]
	ans = min(10 ** 18, indx(m, twos, len2) * 2)
	for i in range(len(ones)):
		ans = min(ans, i + 1 + indx(m - ones[i], twos, len2) * 2)
	print(ans)


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')
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list()
	b = list()
	v1 = list(map(int, input().split()))
	v2 = list(map(int, input().split()))
	for i in range(n):
		if v2[i] == 1:
			a.append(v1[i])
		else:
			b.append(v1[i])
	a.sort(reverse=True)
	b.sort(reverse=True)
	csuma = 0
	r = len(b)
	csumb = sum(b)
	ans = math.inf
	for l in range(0, len(a) + 1):
		while r > 0 and csuma + csumb - b[r - 1] >= m:
			r -= 1
			csumb -= b[r]
		if csumb + csuma >= m:
			ans = min(ans, 2 * r + l)
		if l != len(a):
			csuma += a[l]
	if ans == math.inf:
		print(-1)
	else:
		print(ans)


t = int(input())
for j in range(t):
	(n, m) = tuple(map(int, input().split(' ')))
	a = list(map(int, input().split(' ')))
	b = list(map(int, input().split(' ')))
	one = []
	two = []
	for i in range(n):
		if b[i] == 1:
			one.append(a[i])
		else:
			two.append(a[i])
	two.sort(key=lambda x: -x)
	one.sort(key=lambda x: -x)
	(sum1, sum2) = (0, sum(two))
	r = len(two)
	INF = 9999999999999
	ans = INF
	for i in range(len(one) + 1):
		while r > 0 and sum1 + sum2 - two[r - 1] >= m:
			sum2 -= two[r - 1]
			r -= 1
		if sum1 + sum2 >= m:
			ans = min(ans, i + 2 * r)
		if i < len(one):
			sum1 += one[i]
	print('-1' if ans == INF else str(ans))


import sys
sys.setrecursionlimit(10 ** 6)
from bisect import bisect_left, bisect_right
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	mem = [int(x) for x in input().split()]
	val = [int(x) for x in input().split()]
	if sum(mem) < k:
		print(-1)
		continue
	one = []
	two = []
	for i in range(n):
		if val[i] == 1:
			one.append(mem[i])
		else:
			two.append(mem[i])
	onepre = []
	temp = 0
	one.sort(reverse=True)
	two.sort(reverse=True)
	for i in one:
		temp += i
		onepre.append(temp)
	temp = 0
	twopre = []
	for i in two:
		temp += i
		twopre.append(temp)
	ans = 10 ** 10
	indd = bisect_left(twopre, k)
	if indd != len(twopre):
		ans = min(ans, 2 * (indd + 1))
	for i in range(len(one)):
		x = onepre[i]
		if x >= k:
			ans = min(ans, i + 1)
		ind = bisect_left(twopre, k - x)
		if ind == len(twopre):
			continue
		ans = min(ans, i + 1 + 2 * (ind + 1))
	print(ans)


import sys
import math

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

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

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

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

def FACT(n, mod):
	s = 1
	facts = [1]
	for i in range(1, n + 1):
		s *= i
		s %= mod
		facts.append(s)
	return facts[n]

def C(n, k, mod):
	return FACT(n, mod) * pow(FACT(k, mod) * FACT(n - k, mod) % mod, mod - 2, mod) % mod
t = II()
for i in range(t):
	(n, m) = MI()
	a = LI()
	b = LI()
	ones = []
	twos = []
	for i in range(n):
		if b[i] == 1:
			ones.append(a[i])
		else:
			twos.append(a[i])
	ones.sort(reverse=True)
	twos.sort(reverse=True)
	l = 0
	l1 = 0
	ans = 3 * n
	s = 0
	while l < len(ones) and s < m:
		s += ones[l]
		l += 1
	if s >= m:
		ans = l
	l -= 1
	for i in range(len(twos)):
		s += twos[l1]
		l1 += 1
		while l >= 0 and s - ones[l] >= m:
			s -= ones[l]
			l -= 1
		if s >= m:
			ans = min(ans, l + 1 + 2 * l1)
	print(ans if ans != 3 * n else -1)


import sys, math
from collections import defaultdict
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	su = sum(a)
	if su < m:
		print(-1)
		continue
	(l1, l2) = ([], [])
	for i in range(n):
		if b[i] == 1:
			l1.append(a[i])
		else:
			l2.append(a[i])
	l1.sort(reverse=True)
	l2.sort(reverse=True)
	s = 0
	points = float('inf')
	for i in range(len(l1)):
		s += l1[i]
		if s >= m:
			points = min(points, i + 1)
	if s < m:
		c = len(l1)
		for i in range(len(l2)):
			s += l2[i]
			c += 2
			if s >= m:
				points = min(points, c)
				break
	p2 = 0
	s = sum(l1)
	for i in range(len(l1) - 1, -1, -1):
		s -= l1[i]
		while p2 < len(l2) and s < m:
			s += l2[p2]
			p2 += 1
		if s >= m:
			points = min(points, i + 2 * p2)
	print(points)


def bisect(b, m):
	(l, h, ind) = (0, len(b) - 1, -1)
	while l <= h:
		mid = (l + h) // 2
		if b[mid] >= m:
			ind = mid
			h = mid - 1
		else:
			l = mid + 1
	return ind

def answer(m):
	(c1, c2) = ([0], [])
	for i in range(n):
		if b[i] == 1:
			c1.append(a[i])
		else:
			c2.append(a[i])
	c1.sort(reverse=True)
	c2.sort(reverse=True)
	c1.insert(0, 0)
	(i, j, ans) = (0, 0, 0)
	for i in range(1, len(c2)):
		c2[i] += c2[i - 1]
	ans = 10 ** 8
	for i in range(len(c1)):
		m -= c1[i]
		if m <= 0:
			ans = min(ans, i)
			break
		val = bisect(c2, m)
		if val != -1:
			ans = min(ans, i + (val + 1) * 2)
	if ans == 10 ** 8:
		return -1
	else:
		return ans
for T in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	print(answer(m))


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, m) = map(int, input().split())
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		if sum(a) < m:
			print(-1)
			continue
		ans = sum(b)
		(one, two) = ([], [])
		for j in range(n):
			if b[j] == 1:
				one.append([j, a[j]])
			else:
				two.append([j, a[j]])
		res = []
		so = sorted(one, key=lambda x: -x[1])
		st = sorted(two, key=lambda x: -x[1])
		v = 0
		for j in range(len(so)):
			if v < m:
				v += so[j][1]
				res.append(so[j][0])
			else:
				break
		score = len(res)
		if len(st) == 0:
			print(min(ans, score))
			continue
		res.reverse()
		(l, r) = (0, 0)
		while r < len(st):
			while r < len(st) and v < m:
				score += 2
				v += st[r][1]
				res.append(st[r][0])
				r += 1
			while v >= m:
				ans = min(ans, score)
				if len(res) == 0:
					break
				index = res.pop(0)
				score -= b[index]
				v -= a[index]
		print(ans)
main()


for i in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	one = []
	two = []
	l1 = l2 = 0
	for j in range(n):
		if b[j] == 1:
			one.append(a[j])
			l1 += 1
		else:
			two.append(a[j])
			l2 += 1
	one.sort(reverse=True)
	two.sort(reverse=True)
	for j in range(1, l1):
		one[j] += one[j - 1]
	for j in range(1, l2):
		two[j] += two[j - 1]
	if sum(a) < m:
		print(-1)
	else:
		points = 100000000000
		for j in range(l2):
			if two[j] >= m:
				points = min(points, 2 * (j + 1))
				break
		for j in range(l1):
			if one[j] >= m:
				points = min(points, j + 1)
				break
		j = 0
		k = l2 - 1
		while j != l1 and k != -1:
			if one[j] + two[k] < m:
				j += 1
			else:
				points = min(points, j + 1 + 2 * (k + 1))
				k -= 1
		print(points)


import sys
MOD = 1000000007
import math

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

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

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

def write_line(out):
	return sys.stdout.write(str(out) + '\n')

def solve():
	(n, m) = get_ints()
	mem = list(get_ints())
	points = list(get_ints())
	ones = []
	twos = []
	total_points = 0
	for i in range(n):
		if points[i] == 1:
			ones.append(mem[i])
			total_points += 1
		else:
			twos.append(mem[i])
			total_points += 2
	ones.sort(reverse=True)
	twos.sort(reverse=True)
	if m > sum(mem):
		return -1
	dp = [[0, 0, 0] for i in range(total_points + 1)]
	if ones:
		dp[1] = [ones[0], 1, 0]
	for i in range(2, len(dp)):
		prev_one = dp[i - 1]
		prev_two = dp[i - 2]
		ans1 = 0
		ans2 = 0
		if prev_one[1] < len(ones):
			ans1 = prev_one[0] + ones[prev_one[1]]
		if prev_two[2] < len(twos):
			ans2 = prev_two[0] + twos[prev_two[2]]
		if ans1 >= ans2:
			(dp[i][0], dp[i][1], dp[i][2]) = (ans1, prev_one[1] + 1, prev_one[2])
		else:
			(dp[i][0], dp[i][1], dp[i][2]) = (ans2, prev_two[1], prev_two[2] + 1)
	for i in range(len(dp)):
		if dp[i][0] >= m:
			return i
t = get_int()
while t:
	write_line(solve())
	t -= 1


def clean(apps, free, app_mem, points):
	if sum(app_mem) < free:
		return -1
	elif sum(app_mem) == free:
		return sum(points)
	else:
		(s2, s1) = (0, 0)
		(mem1, mem2) = ([], [])
		for i in range(apps):
			if points[i] == 1:
				mem1.append(app_mem[i])
			else:
				mem2.append(app_mem[i])
				s2 += app_mem[i]
		(mem1.sort(reverse=True), mem2.sort(reverse=True))
		ans = float('inf')
		k = len(mem2) - 1
		for j in range(len(mem1) + 1):
			while k >= 0 and s2 - mem2[k] + s1 >= free:
				s2 -= mem2[k]
				k -= 1
			if s1 + s2 >= free:
				ans = min(ans, 2 * (k + 1) + j)
			if j < len(mem1):
				s1 += mem1[j]
		return ans
for test in range(int(input())):
	(n, m) = map(int, input().split())
	memory = list(map(int, input().split()))
	pts = list(map(int, input().split()))
	print(clean(n, m, memory, pts))


t = int(input())
while t > 0:
	t -= 1
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = []
	d = []
	for i in range(len(b)):
		if b[i] == 1:
			c.append(a[i])
		else:
			d.append(a[i])
	c.sort(reverse=True)
	d.sort(reverse=True)
	if sum(a) < m:
		print(-1)
	else:
		s1 = [0]
		s2 = [0]
		for f in c:
			s1.append(s1[-1] + f)
		for f in d:
			s2.append(s2[-1] + f)
		ans = 10 ** 9
		ind = len(s2) - 1
		for i in range(len(s1)):
			x = s1[i]
			while x + s2[ind] >= m:
				ans = min(ans, i + ind * 2)
				if ind > 0:
					ind -= 1
				else:
					break
		if ans == 10 ** 9:
			print(-1)
		else:
			print(ans)


cases = int(input())
for i in range(cases):
	(n, m) = map(int, input().split())
	twos = []
	ones = []
	mem = list(map(int, input().split()))
	conv = list(map(int, input().split()))
	for i in range(n):
		if conv[i] == 2:
			twos.append(mem[i])
		else:
			ones.append(mem[i])
	twos.sort()
	ones.sort()
	convCount = 0
	while m > 0 and twos and ones:
		if ones[-1] >= m:
			convCount += 1
			m -= ones.pop()
			break
		elif twos[-1] >= m:
			convCount += 2
			m -= twos.pop()
			break
		if len(ones) == 1 or twos[-1] > ones[-1] + ones[-2]:
			convCount += 2
			m -= twos.pop()
		else:
			convCount += 1
			m -= ones.pop()
	while m > 0 and ones:
		convCount += 1
		m -= ones.pop()
	while m > 0 and twos:
		convCount += 2
		m -= twos.pop()
	print(convCount if m <= 0 else -1)


t = int(input())
while t != 0:
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	one = []
	two = []
	for i in range(n):
		if b[i] == 1:
			one.append(a[i])
		else:
			two.append(a[i])
	one.sort()
	two.sort()
	ans = 0
	while len(one) > 0 and len(two) > 0 and (m > 0):
		if one[-1] >= m:
			ans += 1
			m -= one[-1]
			one.pop()
			break
		elif m <= two[-1]:
			ans += 2
			m -= two[-1]
			two.pop()
			break
		elif len(one) == 1:
			ans += 2
			m -= two[-1]
			two.pop()
		elif two[-1] > one[-1] + one[-2]:
			ans += 2
			m -= two[-1]
			two.pop()
		else:
			m -= one[-1]
			ans += 1
			one.pop()
	if m <= 0:
		print(ans)
	else:
		while len(one) > 0 and m > 0:
			ans += 1
			m -= one[-1]
			one.pop()
		if m <= 0:
			print(ans)
		else:
			while len(two) > 0 and m > 0:
				ans += 2
				m -= two[-1]
				two.pop()
			if m <= 0:
				print(ans)
			else:
				print(-1)
	t -= 1


from bisect import bisect_left, bisect_right
T = int(input())
for i in range(T):
	v1 = []
	v2 = []
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(n):
		if b[i] == 1:
			v1.append(a[i])
		else:
			v2.append(a[i])
	v1.sort(reverse=True)
	v2.sort(reverse=True)
	ls1 = []
	ls2 = []
	temp = 0
	for i in v1:
		temp += i
		ls1.append(temp)
	temp = 0
	for i in v2:
		temp += i
		ls2.append(temp)
	ls1.insert(0, 0)
	ls2.insert(0, 0)
	ans = float('inf')
	for i in range(len(ls1)):
		cur = bisect_left(ls2, m - ls1[i])
		if cur >= len(ls2):
			cur -= 1
		if ls1[i] + ls2[cur] >= m:
			ans = min(ans, i + 2 * cur)
	if ans == float('inf'):
		print(-1)
	else:
		print(ans)


def find():
	(n, m) = map(int, input().split())
	mem = tuple(input().split())
	val = tuple(input().split())
	a = []
	b = []
	for i in range(n):
		a.append(int(mem[i])) if int(val[i]) == 1 else b.append(int(mem[i]))
	a.sort(reverse=True)
	b.sort(reverse=True)
	sumA = 0
	sumB = sum(b)
	j = len(b)
	res = 0
	for i in range(len(a) + 1):
		while j > 0 and sumA + sumB - b[j - 1] >= m:
			j -= 1
			sumB -= b[j]
		if sumA + sumB >= m:
			tmp = i + 2 * j
			res = res or tmp
			res = min(res, tmp)
		if i != len(a):
			sumA += a[i]
	print(res if res else -1)
for i in range(int(input())):
	find()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	Q = sum(a) - m
	if Q < 0:
		print(-1)
	else:
		l1 = sorted([x for (i, x) in enumerate(a) if b[i] == 1])
		l2 = sorted([x for (i, x) in enumerate(a) if b[i] == 2])
		for i in range(1, len(l1)):
			l1[i] += l1[i - 1]
		for i in range(1, len(l2)):
			l2[i] += l2[i - 1]
		opt = 0
		p = 0
		j = len(l1) - 1
		for i in range(len(l2) + 1):
			c = 2 * i
			if p > Q:
				break
			while j >= 0 and l1[j] > Q - p:
				j -= 1
			c += j + 1
			if c > opt:
				opt = c
			if i < len(l2):
				p = l2[i]
		print(sum(b) - opt)


from sys import stdin
for _ in range(int(input())):
	(n, m) = map(int, stdin.readline().strip().split())
	a = list(map(int, stdin.readline().strip().split()))
	b = list(map(int, stdin.readline().strip().split()))
	s = sum(a)
	sb = sum(b)
	if s < m:
		print(-1)
	elif s == m:
		print(sb)
	else:
		(two, one) = ([], [])
		for i in range(n):
			if b[i] == 1:
				one.append(a[i])
			else:
				two.append(a[i])
		one.sort(reverse=True)
		two.sort(reverse=True)
		(lo, lt) = (len(one), len(two))
		(s1, s2) = ([0] * lo, [0] * lt)
		for i in range(lo):
			if i == 0:
				s1[i] = one[i]
			else:
				s1[i] = s1[i - 1] + one[i]
		for i in range(lt):
			if i == 0:
				s2[i] = two[0]
			else:
				s2[i] = s2[i - 1] + two[i]
		lost = sb
		if lt == 0:
			for i in range(lo):
				if s1[i] >= m:
					lost = i + 1
					break
		else:
			for i in range(lo):
				if s1[i] < m:
					val = s1[i]
					if val + s2[-1] < m:
						continue
					temp = i + 1
					for j in range(lt):
						temp += 2
						if val + s2[j] >= m:
							break
					lost = min(lost, temp)
				else:
					lost = min(lost, i + 1)
					break
		for i in range(lt):
			if s2[i] >= m:
				lost = min(lost, 2 * (i + 1))
				break
		print(lost)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	c = list(map(int, input().split()))
	(o, t, s) = ([], [], 0)
	for i in range(n):
		s += a[i]
		if c[i] == 1:
			o.append(a[i])
		else:
			t.append(a[i])
	if s < m:
		print(-1)
	else:
		o.sort(reverse=True)
		t.sort(reverse=True)
		(i1, i2, M, C) = (0, 0, 0, 0)
		(l1, l2) = (len(o), len(t))
		while M < m:
			(s1, s2) = (0, 0)
			if i1 < l1:
				s1 = o[i1]
				if i1 < l1 - 1:
					s1 += o[i1 + 1]
			if i2 < l2:
				s2 = t[i2]
			if m - M <= s1 or s1 >= s2:
				M += o[i1]
				i1 += 1
				C += 1
			else:
				M += t[i2]
				C += 2
				i2 += 1
		print(C)


def main():
	t = int(input())
	allAns = []
	for _ in range(t):
		(n, m) = readIntArr()
		oneConvenientPt = []
		twoConvenientPts = []
		a = readIntArr()
		b = readIntArr()
		for i in range(n):
			if b[i] == 1:
				oneConvenientPt.append(a[i])
			else:
				twoConvenientPts.append(a[i])
		oneConvenientPt.sort(reverse=True)
		twoConvenientPts.sort(reverse=True)
		twoPrefSums = twoConvenientPts.copy()
		for i in range(1, len(twoPrefSums)):
			twoPrefSums[i] += twoPrefSums[i - 1]
		minConvenientPts = inf
		oneTotal = 0
		oneCnts = 0
		oneConvenientPt = [0] + oneConvenientPt
		for x in oneConvenientPt:
			oneTotal += x
			if oneTotal >= m:
				minConvenientPts = min(minConvenientPts, oneCnts)
			else:
				b = n
				i = -1
				while b > 0:
					while i + b < len(twoPrefSums) and twoPrefSums[i + b] + oneTotal < m:
						i += b
					b //= 2
				i += 1
				if i < len(twoPrefSums):
					twoCnts = i + 1
					convenientPts = oneCnts + 2 * twoCnts
					minConvenientPts = min(minConvenientPts, convenientPts)
			oneCnts += 1
		if minConvenientPts == inf:
			allAns.append(-1)
		else:
			allAns.append(minConvenientPts)
	multiLineArrayPrint(allAns)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]
inf = float('inf')
MOD = 10 ** 9 + 7
main()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	E = sorted(filter(lambda i: B[i] == 1, range(n)), key=A.__getitem__, reverse=True)
	F = sorted(filter(lambda i: B[i] == 2, range(n)), key=A.__getitem__, reverse=True)
	G = [0]
	for e in E:
		G.append(G[-1] + A[e])
	H = [0]
	for f in F:
		H.append(H[-1] + A[f])
	e = 0
	f = len(H) - 1
	r = 10 ** 10
	while e < len(G) and f >= 0:
		if G[e] + H[f] >= m:
			r = min(r, e + 2 * f)
			f -= 1
		else:
			e += 1
	if r == 10 ** 10:
		print(-1)
	else:
		print(r)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	(aa, bb) = ([], [])
	for i in range(n):
		if b[i] == 1:
			aa.append(a[i])
		else:
			bb.append(a[i])
	aa.sort(reverse=True)
	bb.sort(reverse=True)
	pre = 0
	suf = sum(bb)
	r = len(bb)
	out = 10 ** 9
	for i in range(len(aa) + 1):
		while r > 0 and suf + pre - bb[r - 1] >= m:
			r -= 1
			suf -= bb[r]
		if suf + pre >= m:
			out = min(out, r * 2 + i)
		if i < len(aa):
			pre += aa[i]
	if out == 10 ** 9:
		print(-1)
	else:
		print(out)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	x = []
	y = []
	for i in range(len(a)):
		if b[i] == 1:
			x.append(a[i])
		else:
			y.append(a[i])
	x = sorted(x, reverse=True)
	y = sorted(y, reverse=True)
	i = 0
	j = 0
	ans = 0
	lis = []
	while i < len(x) and j < len(y) and (m > 0):
		if x[i] >= m:
			ans += 1
			m -= x[i]
			lis.append(x[i])
			i += 1
		elif x[i] > y[j]:
			ans += 1
			m -= x[i]
			lis.append(x[i])
			i += 1
		elif y[j] >= m:
			ans += 2
			m -= y[j]
			j += 1
		elif 2 * x[i] > y[j]:
			ans += 1
			m -= x[i]
			lis.append(x[i])
			i += 1
		else:
			ans += 2
			m -= y[j]
			j += 1
	while i < len(x) and m > 0:
		ans += 1
		m -= x[i]
		i += 1
	while j < len(y) and m > 0:
		ans += 2
		m -= y[j]
		j += 1
	if m > 0:
		print(-1)
	else:
		while lis != [] and lis[-1] + m <= 0:
			ans -= 1
			m += lis[-1]
			lis.pop()
		print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	mem = list(map(int, input().split()))
	imp = list(map(int, input().split()))
	one = []
	two = []
	for (mi, pi) in zip(mem, imp):
		if pi == 1:
			one.append(mi)
		else:
			two.append(mi)
	one.sort(reverse=True)
	two.sort(reverse=True)
	pone = [0]
	for elm in one:
		pone.append(pone[-1] + elm)
	ptwo = [0]
	for elm in two:
		ptwo.append(ptwo[-1] + elm)
	low = 0
	high = len(one) + 2 * len(two) + 1
	while low < high:
		mid = (low + high) // 2
		max_mem = 0
		max_two = min(mid // 2, len(two))
		for x in range(max_two + 1):
			if mid - 2 * x > len(one):
				max_mem = max(max_mem, pone[-1] + ptwo[x])
				continue
			max_mem = max(max_mem, pone[mid - 2 * x] + ptwo[x])
		if max_mem >= m:
			high = mid
		else:
			low = mid + 1
	if low == len(one) + 2 * len(two) + 1:
		print(-1)
	else:
		print(low)


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, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	one = []
	two = []
	for i in range(n):
		if b[i] == 1:
			one.append(a[i])
		else:
			two.append(a[i])
	i = 0
	j = 0
	one.sort(reverse=True)
	two.sort(reverse=True)
	for i in range(1, len(one)):
		one[i] += one[i - 1]
	for i in range(1, len(two)):
		two[i] += two[i - 1]
	one = [0] + one
	two = [0] + two
	ans = float('inf')
	n1 = len(one)
	n2 = len(two)
	for i in range(n1):
		need = m - one[i]
		if need <= 0:
			ans = min(ans, i)
			continue
		pos = bisect.bisect_left(two, need)
		if pos == n2:
			continue
		elif two[pos] + one[i] < m:
			continue
		else:
			ans = min(ans, i + pos * 2)
	if ans == float('inf'):
		print(-1)
	else:
		print(ans)


def readInt():
	return int(input())

def readInts():
	return [int(x) for x in input().split()]

def readBin():
	return [int(x) for x in readString()]

def readString():
	return input().rstrip()

def readCase():
	return readString()

def solve(n, m, usage, convenience):
	normal = []
	high = []
	max_loss = 2 * n + 1
	for x in range(n):
		if convenience[x] == 1:
			normal.append(usage[x])
		else:
			high.append(usage[x])
	normal.sort(reverse=True)
	high.sort(reverse=True)
	loss = 0
	normalPos = 0
	highPos = 0
	while m > 0 and normalPos < len(normal):
		m -= normal[normalPos]
		normalPos += 1
		loss += 1
	best_loss = max_loss
	if m <= 0:
		best_loss = loss
	normalPos -= 1
	while highPos < len(high):
		m -= high[highPos]
		highPos += 1
		loss += 2
		while normalPos >= 0:
			if m + normal[normalPos] <= 0:
				m += normal[normalPos]
				normalPos -= 1
				loss -= 1
			else:
				break
		if m <= 0 and loss < best_loss:
			best_loss = loss
	if best_loss == max_loss:
		return -1
	else:
		return best_loss
cases = readInt()
for case in range(cases):
	(n, m) = readInts()
	usage = readInts()
	convenience = readInts()
	print(solve(n, m, usage, convenience))


import sys
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	cost1 = []
	cost2 = []
	for i in range(n):
		if b[i] == 1:
			cost1.append(a[i])
		else:
			cost2.append(a[i])
	cost1.sort(reverse=True)
	cost2.sort(reverse=True)
	i = -1
	ans = sys.maxsize
	cost = 0
	total_memory = 0
	while i + 1 < len(cost2) and total_memory < m:
		i += 1
		total_memory += cost2[i]
		cost += 2
	if total_memory >= m:
		ans = min(ans, cost)
	for j in range(len(cost1)):
		total_memory += cost1[j]
		cost += 1
		while i >= 0 and total_memory - cost2[i] >= m:
			cost -= 2
			total_memory -= cost2[i]
			i -= 1
		if total_memory >= m:
			ans = min(ans, cost)
	if ans == sys.maxsize:
		print(-1)
	else:
		print(ans)


import sys, math
import io, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
from itertools import permutations, combinations

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

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
from decimal import Decimal
from fractions import Fraction
sys.setrecursionlimit(100000)
INF = float('inf')
mod = 10 ** 9 + 7
for t in range(int(data())):
	(n, m) = mdata()
	a = mdata()
	b = mdata()
	if sum(a) < m:
		out(-1)
		continue
	(l1, l2) = ([], [])
	for i in range(n):
		if b[i] == 1:
			l1.append(a[i])
		else:
			l2.append(a[i])
	l1.sort()
	l2.sort()
	ans = 0
	ans1 = 0
	while m > 0:
		if len(l1) and m <= l1[-1]:
			ans += 1
			m -= l1.pop()
		elif len(l1) > 1:
			if len(l2) and l2[-1] >= l1[-1] + l1[-2]:
				m -= l2.pop()
				ans += 2
			else:
				m -= l1.pop()
				ans += 1
		else:
			m -= l2.pop()
			ans += 2
	if ans1:
		ans = min(ans, ans1)
	out(ans)


import sys
import bisect as bi
import math
from collections import defaultdict as dd
from types import GeneratorType
input = sys.stdin.readline
mo = 10 ** 9 + 7

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

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

def inin():
	return int(input())

def msb(n):
	n |= n >> 1
	n |= n >> 2
	n |= n >> 4
	n |= n >> 8
	n |= n >> 16
	n |= n >> 32
	n |= n >> 64
	return n - (n >> 1)

def pref(a, n, f):
	pre = [0] * n
	if f == 0:
		pre[0] = a[0]
		for i in range(1, n):
			pre[i] = a[i] + pre[i - 1]
	else:
		pre[-1] = a[-1]
		for i in range(n - 2, -1, -1):
			pre[i] = pre[i + 1] + a[i]
	return pre
for _ in range(inin()):
	(n, m) = cin()
	l = ain()
	p = ain()
	one = []
	two = []
	for i in range(n):
		if p[i] == 1:
			one += [l[i]]
		else:
			two += [l[i]]
	su = sum(l)
	lo = len(one)
	lt = len(two)
	if su < m:
		print(-1)
	else:
		one.sort(reverse=True)
		two.sort(reverse=True)
		lo = len(one)
		lt = len(two)
		ans = n * 2
		if lo:
			preo = pref(one, lo, 0)
		if lt:
			pret = pref(two, lt, 0)
		if lo == 0:
			pos = bi.bisect(pret, m)
			if pret[pos - 1] != m:
				pos += 1
			ans = pos * 2
		elif lt == 0:
			pos = bi.bisect(preo, m)
			if preo[pos - 1] != m:
				pos += 1
			ans = pos
		else:
			for i in range(lo):
				temp = m - preo[i]
				if temp <= 0:
					ans = min(ans, i + 1)
					break
				pos = bi.bisect(pret, temp)
				if pos == lt:
					if pret[pos - 1] != temp:
						continue
				elif pret[pos - 1] != temp:
					pos += 1
				ans = min(ans, 2 * pos + i + 1)
			for i in range(lt):
				temp = m - pret[i]
				if temp <= 0:
					ans = min(ans, 2 * (i + 1))
					break
				pos = bi.bisect(preo, temp)
				if pos == lo:
					if preo[pos - 1] != temp:
						continue
				elif preo[pos - 1] != temp:
					pos += 1
				ans = min(ans, pos + 2 * (i + 1))
		print(ans)

def msb(n):
	n |= n >> 1
	n |= n >> 2
	n |= n >> 4
	n |= n >> 8
	n |= n >> 16
	n |= n >> 32
	n |= n >> 64
	return n - (n >> 1)

def pref(a, n, f):
	pre = [0] * n
	if f == 0:
		pre[0] = a[0]
		for i in range(1, n):
			pre[i] = a[i] + pre[i - 1]
	else:
		pre[-1] = a[-1]
		for i in range(n - 2, -1, -1):
			pre[i] = pre[i + 1] + a[i]
	return pre

def kadane(A):
	maxSoFar = maxEndingHere = start = end = beg = 0
	for i in range(len(A)):
		maxEndingHere = maxEndingHere + A[i]
		if maxEndingHere < 0:
			maxEndingHere = 0
			beg = i + 1
		if maxSoFar < maxEndingHere:
			maxSoFar = maxEndingHere
			start = beg
			end = i
	return (maxSoFar, start, end)

def modFact(n, p):
	if n < 0:
		return 0
	if n >= p:
		return 0
	result = 1
	for i in range(1, n + 1):
		result = result * i % p
	return result

def ncr(n, r, p):
	if n < r or n < 0:
		return 0
	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 bootstrap(f, stack=[]):

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


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
from math import inf, log2

class SegmentTree:

	def __init__(self, array, func=max):
		self.n = len(array)
		self.size = 2 ** (int(log2(self.n - 1)) + 1) if self.n != 1 else 1
		self.func = func
		self.default = 0 if self.func != min else inf
		self.data = [self.default] * (2 * self.size)
		self.process(array)

	def process(self, array):
		self.data[self.size:self.size + self.n] = array
		for i in range(self.size - 1, -1, -1):
			self.data[i] = self.func(self.data[2 * i], self.data[2 * i + 1])

	def query(self, alpha, omega):
		if alpha == omega:
			return self.data[alpha + self.size]
		res = self.default
		alpha += self.size
		omega += self.size + 1
		while alpha < omega:
			if alpha & 1:
				res = self.func(res, self.data[alpha])
				alpha += 1
			if omega & 1:
				omega -= 1
				res = self.func(res, self.data[omega])
			alpha >>= 1
			omega >>= 1
		return res

	def update(self, index, value):
		index += self.size
		self.data[index] = value
		index >>= 1
		while index:
			self.data[index] = self.func(self.data[2 * index], self.data[2 * index + 1])
			index >>= 1
for _ in range(int(input()) if True else 1):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	(ax, ay) = ([], [])
	for i in range(n):
		if b[i] == 1:
			ax += [a[i]]
		else:
			ay += [a[i]]
	ans = inf
	(ax, ay) = (sorted(ax, reverse=True), sorted(ay))
	st = SegmentTree([0] + ax, func=lambda a, b: a + b)
	k = 0
	points = 0
	(alpha, omega) = (0, len(ax))
	while alpha < omega:
		mid = (alpha + omega) // 2
		if points + st.query(0, mid) >= m:
			omega = mid
		else:
			alpha = mid + 1
	if st.query(0, alpha) + points >= m:
		ans = min(ans, alpha)
	while ay:
		k += 1
		points += ay.pop()
		(alpha, omega) = (0, len(ax))
		while alpha < omega:
			mid = (alpha + omega) // 2
			if points + st.query(0, mid) >= m:
				omega = mid
			else:
				alpha = mid + 1
		pp = st.query(0, alpha) + points
		if pp >= m:
			ans = min(ans, 2 * k + alpha)
	print(ans if ans != inf else -1)


class app:
	a = 0
	b = 0

	def __init__(self, a, b):
		self.a = a
		self.b = b

def cmp(app):
	return app.a

def solve():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	arr = []
	for i in range(n):
		arr.append(app(a[i], b[i]))
	arr = sorted(arr, key=cmp)
	sum = 0
	msum = 0
	twos = []
	ones = []
	for i in range(n - 1, -1, -1):
		if sum < m:
			sum += arr[i].a
			msum += arr[i].b
			if arr[i].b == 2:
				twos.append(arr[i].a)
		elif arr[i].b == 1:
			ones.append(arr[i].a)
	ind = 0
	while ind < len(ones) and twos:
		if sum - twos[-1] + ones[ind] >= m:
			sum = sum - twos[-1] + ones[ind]
			msum -= 1
			ind += 1
			twos.pop()
		elif ind + 1 < len(ones) and sum - twos[-1] + ones[ind] + ones[ind + 1] >= m:
			sum = sum - twos[-1] + ones[ind] + ones[ind + 1]
			ind += 2
			twos.pop()
		else:
			break
	if sum >= m:
		print(msum)
	else:
		print(-1)

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


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	arrA = []
	arrB = []
	for i in range(n):
		if b[i] == 1:
			arrA.append(a[i])
		else:
			arrB.append(a[i])
	arrA.sort(reverse=True)
	arrB.sort(reverse=True)
	if sum(a) < m:
		print(-1)
	else:
		i = 0
		j = 0
		space = 0
		ans = 0
		while space < m:
			if i < len(arrA):
				space += arrA[i]
				i += 1
				ans += 1
			else:
				space += arrB[j]
				j += 1
				ans += 2
		i -= 1
		mini = ans
		flag = True
		while i > -1:
			space -= arrA[i]
			ans -= 1
			i -= 1
			while space < m and j < len(arrB):
				space += arrB[j]
				j += 1
				ans += 2
			if space < m:
				flag = False
				break
			if ans < mini:
				mini = ans
		print(mini)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	x = []
	y = []
	for i in range(n):
		if b[i] == 1:
			x.append(a[i])
		else:
			y.append(a[i])
	x.sort(reverse=True)
	y.sort(reverse=True)
	(t, cost) = (0, 0)
	p2 = -1
	ans = 210000000000
	while p2 + 1 < len(y) and t < m:
		p2 += 1
		t += y[p2]
		cost += 2
	if t >= m:
		ans = min(ans, cost)
	for i in range(len(x)):
		t += x[i]
		cost += 1
		while p2 >= 0 and t - y[p2] >= m:
			t -= y[p2]
			p2 -= 1
			cost -= 2
		if t >= m:
			ans = min(ans, cost)
	if ans >= 210000000000:
		print(-1)
	else:
		print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	memoryCost = list(map(int, input().split()))
	convPoints = list(map(int, input().split()))
	cost1 = list()
	cost2 = list()
	for (mem, conv) in zip(memoryCost, convPoints):
		if conv == 1:
			cost1.append(mem)
		else:
			cost2.append(mem)
	cost1.sort(reverse=True)
	cost2.sort(reverse=True)
	memory = sum(cost2)
	convP = 2 * len(cost2)
	twoCostPointer = len(cost2) - 1
	ans = float('inf')
	for x in range(-1, len(cost1)):
		if x >= 0:
			convP += 1
			memory += cost1[x]
		while twoCostPointer >= 0 and memory - cost2[twoCostPointer] >= m:
			memory -= cost2[twoCostPointer]
			twoCostPointer -= 1
			convP -= 2
		if memory >= m:
			ans = min(ans, convP)
	print(ans if ans != float('inf') else -1)


from bisect import *
import math
a = int(input())
for i in range(a):
	(n, m) = map(int, input().split())
	z1 = list(map(int, input().split()))
	z2 = list(map(int, input().split()))
	a1 = []
	a2 = []
	for i in range(len(z1)):
		if z2[i] == 1:
			a1.append(z1[i])
		else:
			a2.append(z1[i])
	a1.sort(reverse=True)
	a2.sort(reverse=True)
	for i in range(1, len(a1)):
		a1[i] += a1[i - 1]
	for i in range(1, len(a2)):
		a2[i] += a2[i - 1]
	mini = math.inf
	r = bisect_left(a1, m)
	if r != len(a1):
		mini = r + 1
	for i in range(len(a2)):
		r = bisect_left(a1, m - a2[i])
		if r != len(a1):
			mini = min(mini, r + 1 + 2 * (i + 1))
	r = bisect_left(a2, m)
	if r != len(a2):
		mini = min(mini, 2 * (r + 1))
	if mini == math.inf:
		print(-1)
	else:
		print(mini)


cases = int(input())
for _ in range(cases):
	(n, m) = [int(i) for i in input().strip().split()]
	mem = [int(i) for i in input().strip().split()]
	points = [int(i) for i in input().strip().split()]
	ones = [(mem[i], points[i]) for i in range(n) if points[i] == 1]
	twos = [(mem[i], points[i]) for i in range(n) if points[i] == 2]
	ones.sort()
	twos.sort()
	ans = 0
	while m > 0 and (ones or twos):
		if not twos or (ones and m - ones[-1][0] <= 0):
			m -= ones.pop()[0]
			ans += 1
		elif not ones:
			m -= twos.pop()[0]
			ans += 2
		else:
			oneSum = sum((x[0] for x in ones[-2:]))
			twoSum = twos[-1][0]
			if oneSum >= twoSum:
				m -= ones.pop()[0]
				ans += 1
			else:
				m -= twos.pop()[0]
				ans += 2
	print(ans if m <= 0 else -1)


t = int(input())
for _ in range(t):
	(n, g) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	if g > sum(a):
		print(-1)
		continue
	(p1, p2) = ([], [])
	for i in range(n):
		if b[i] == 1:
			p1.append(a[i])
		else:
			p2.append(a[i])
	(p1, p2) = (sorted(p1, reverse=True), sorted(p2, reverse=True))
	(i, j, sp1, sp2, o) = (-1, len(p2) - 1, 0, sum(p2), 2 * n + 1)
	for i in range(-1, len(p1)):
		if i >= 0:
			sp1 += p1[i]
		while j >= 0 and sp1 + sp2 - p2[j] >= g:
			sp2 -= p2[j]
			j -= 1
		if sp1 + sp2 >= g:
			o = min(o, i + 1 + 2 * (j + 1))
	print(o)


t = int(input())
for i in range(t):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	if sum(a) < m:
		print(-1)
	else:
		one_arr = []
		two_arr = []
		for (app, score) in zip(a, b):
			if score == 1:
				one_arr.append(app)
			else:
				two_arr.append(app)
		one_arr.sort()
		two_arr.sort()
		counter = 0
		while m > 0:
			if len(one_arr) == 0:
				m -= two_arr[-1]
				del two_arr[-1]
				counter += 2
			elif len(two_arr) == 0:
				m -= one_arr[-1]
				del one_arr[-1]
				counter += 1
			elif m <= one_arr[-1]:
				m -= one_arr[-1]
				counter += 1
				del one_arr[-1]
			elif len(one_arr) > 1:
				if one_arr[-1] + one_arr[-2] > two_arr[-1]:
					m -= one_arr[-1]
					counter += 1
					del one_arr[-1]
				else:
					m -= two_arr[-1]
					counter += 2
					del two_arr[-1]
			else:
				m -= two_arr[-1]
				counter += 2
				del two_arr[-1]
		print(counter)


from collections import *
from bisect 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()
pre = [1]
p = 10 ** 9 + 7
for i in range(1, 1009):
	pre.append(pre[-1] * i % p)
while t:
	t -= 1
	(n, m) = ma()
	a = lis()
	b = lis()
	oe = []
	se = []
	for i in range(n):
		if b[i] == 1:
			oe.append(a[i])
		else:
			se.append(a[i])
	pro = [0]
	prs = [0]
	fl = 0
	r = float('inf')
	if len(oe):
		oe.sort(reverse=True)
		for i in oe:
			pro.append(pro[-1] + i)
		if pro[-1] >= m:
			l = bisect_left(pro, m)
			r = min(r, l)
			fl = 1
	if len(se):
		se.sort(reverse=True)
		for i in se:
			prs.append(prs[-1] + i)
		if prs[-1] >= m:
			l = bisect_left(prs, m)
			r = min(r, 2 * l)
			fl = 1
		for i in range(1, len(pro)):
			ha = pro[i]
			re = m - pro[i]
			if re > 0 and re <= prs[-1]:
				l = bisect_left(prs, re)
				r = min(r, i + 2 * l)
				fl = 1
	for i in range(1, len(prs)):
		ha = prs[i]
		re = m - ha
		if re > 0 and re <= pro[-1]:
			l = bisect_left(pro, re)
			r = min(r, i * 2 + l)
			fl = 1
	if fl == 0:
		r = -1
	print(r)


import sys
input = sys.stdin.readline

def solution(n, m, a, b):
	l_1 = []
	l_2 = []
	diff_memory = 0
	sol = 10 ** 10
	sum_a = sum(a)
	if sum_a < m:
		print(-1)
		return
	l_1 = [ai for (ai, bi) in zip(a, b) if bi == 1]
	l_2_slave = [ai for (ai, bi) in zip(a, b) if bi == 2]
	l_1.sort(reverse=True)
	l_2_slave.sort(reverse=True)
	l_2 = []
	for i in range(-1, 2 * len(l_2_slave) - 1):
		if i % 2 == 1:
			l_2.append(0)
		else:
			l_2.append(l_2_slave[i // 2])
	partial_l1 = [0]
	for elem in l_1:
		partial_l1.append(partial_l1[-1] + elem)
	partial_l2 = [0]
	for elem in l_2:
		partial_l2.append(partial_l2[-1] + elem)
	i1 = len(partial_l1) - 1
	for i2 in range(len(partial_l2)):
		while i1 >= 0:
			if partial_l1[i1] + partial_l2[i2] >= m:
				sol = min(sol, i1 + i2)
				i1 -= 1
			else:
				break
	print(sol)
T = int(input())
for t in range(T):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	solution(n, m, a, b)


import sys
import heapq
t = int(sys.stdin.readline())
for _ in range(t):
	(n, m) = map(int, sys.stdin.readline().split())
	a = list(map(int, sys.stdin.readline().split()))
	b = list(map(int, sys.stdin.readline().split()))
	if sum(a) < m:
		print(-1)
		continue
	(pq1, pq2) = ([], [])
	for i in range(n):
		if b[i] == 1:
			heapq.heappush(pq1, -a[i])
		else:
			heapq.heappush(pq2, -a[i])
	answer = 0
	(curMemory, curCost) = (0, 0)
	while len(pq1) >= 2 and len(pq2) >= 1:
		if curMemory - pq1[0] >= m:
			answer = curCost + 1
			break
		elif curMemory - pq2[0] >= m:
			answer = curCost + 2
			break
		temp = -heapq.heappop(pq1)
		if temp - pq1[0] <= -pq2[0]:
			curCost += 2
			curMemory += -heapq.heappop(pq2)
			heapq.heappush(pq1, -temp)
		else:
			curCost += 1
			curMemory += temp
	if curMemory >= m:
		answer = curCost
	if answer > 0:
		print(answer)
	else:
		if len(pq2) == 0:
			while curMemory < m:
				curMemory += -heapq.heappop(pq1)
				curCost += 1
			answer = curCost
		elif len(pq1) == 0:
			while curMemory < m:
				curMemory += -heapq.heappop(pq2)
				curCost += 2
			answer = curCost
		else:
			while curMemory < m:
				if curMemory - pq1[0] >= m:
					curCost += 1
					break
				if len(pq2) > 0:
					curMemory += -heapq.heappop(pq2)
					curCost += 2
			answer = curCost
		print(answer)


import sys
import bisect

def amin(x, y):
	if x > y:
		x = y
	return x

def solve():
	(n, m) = map(int, input().split())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	zip1 = zip(a, b)
	zip1 = sorted(zip1, reverse=True)
	(a, b) = zip(*zip1)
	zip1 = zip(b, a)
	zip1 = sorted(zip1, reverse=True)
	(b, a) = zip(*zip1)
	a = list(a)
	b = list(b)
	try:
		index_1 = b.index(1)
	except ValueError:
		index_1 = len(a)
	for i in range(1, index_1):
		a[i] = a[i] + a[i - 1]
	for i in range(index_1 + 1, n):
		a[i] = a[i] + a[i - 1]
	p1 = [a[i] for i in range(index_1, n)]
	p2 = [a[i] for i in range(0, index_1)]
	ans = sys.maxsize
	for i in range(0, len(p2) + 1):
		sum = 0
		cost = 2 * i
		if i > 0:
			sum = p2[i - 1]
		if sum >= m:
			ans = amin(ans, cost)
		k = bisect.bisect_left(p1, m - sum)
		if k < len(p1):
			ans = amin(ans, cost + k + 1)
	if ans == sys.maxsize:
		ans = -1
	print(ans)
t = int(input())
for i in range(t):
	solve()


import sys
import collections
input = sys.stdin.readline

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

def solve():
	(n, m) = map(int, input().split())
	numberOfMemoryUnits = list(map(int, input().split()))
	conveniencePoints = list(map(int, input().split()))
	if sum(numberOfMemoryUnits) < m:
		println('-1')
		return
	ones = []
	twos = []
	for i in range(n):
		if conveniencePoints[i] == 1:
			ones += [numberOfMemoryUnits[i]]
		else:
			twos += [numberOfMemoryUnits[i]]
	ones.sort(reverse=True)
	twos.sort(reverse=True)
	twosSum = sum(twos)
	ans = 10 ** 69
	(one, two) = (0, 0)
	runSum = 0
	while one != len(ones) and runSum < m:
		runSum += ones[one]
		one += 1
	while two != len(twos) and runSum < m:
		runSum += twos[two]
		two += 1
	ans = one + two * 2
	while one != 0:
		one -= 1
		runSum -= ones[one]
		while two != len(twos) and runSum < m:
			runSum += twos[two]
			two += 1
		if runSum >= m:
			ans = min(ans, one + two * 2)
		else:
			break
	print(ans)
for _ in range(int(input()) if 1 else 1):
	solve()


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ones = []
	twos = []
	for i in range(n):
		if b[i] == 1:
			ones.append(a[i])
		else:
			twos.append(a[i])
	ones.sort()
	ones.reverse()
	twos.sort()
	twos.reverse()
	ans = -1
	pointer1 = 0
	pointer2 = 0
	tmp = 0
	while pointer1 < len(ones):
		tmp += ones[pointer1]
		pointer1 += 1
		if tmp >= m:
			break
	while tmp < m and pointer2 < len(twos):
		tmp += twos[pointer2]
		pointer2 += 1
		if tmp >= m:
			break
	if tmp < m:
		print(-1)
		continue
	ans = pointer1 + 2 * pointer2
	for i in range(pointer1 - 1, -1, -1):
		tmp -= ones[i]
		while tmp < m and pointer2 < len(twos):
			tmp += twos[pointer2]
			pointer2 += 1
			if tmp >= m:
				break
		if tmp < m:
			break
		ans = min(ans, i + 2 * pointer2)
	print(ans)


import sys
t = int(input())
for _ in range(0, t, 1):
	(n, m) = map(int, input().split())
	(one, two, x, ok, mini) = ([], [], 0, False, 2 * n + 10)
	A = [int(a) for a in input().split()]
	B = [int(a) for a in input().split()]
	for i in range(0, n, 1):
		if B[i] == 1:
			one.append(A[i])
		else:
			two.append(A[i])
	one.sort(reverse=True)
	two.sort(reverse=True)
	one.insert(0, 0)
	two.insert(0, 0)
	for i in range(1, len(two), 1):
		two[i] += two[i - 1]
	for i in range(0, len(one), 1):
		x += one[i]
		(hi, lo, mid, ans) = (len(two) - 1, 0, 0, 0)
		while hi >= lo:
			mid = int((hi + lo) / 2)
			if x + two[mid] >= m:
				hi = mid - 1
				ans = mid
			else:
				lo = mid + 1
		if x + two[ans] >= m:
			ok = True
			mini = min(mini, 2 * ans + i)
	if ok == True:
		print(mini)
	else:
		print(-1)


import math
import sys
from collections import *
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())
t = inp()
ret = []
for i in range(t):
	(n, m) = inlt()
	mems = inlt()
	convs = inlt()
	if sum(mems) < m:
		ret.append(-1)
		continue
	low = []
	high = []
	for i in range(n):
		if convs.pop() == 1:
			low.append(mems.pop())
		else:
			high.append(mems.pop())
	low.sort()
	high.sort()
	cur = 0
	loss = 0
	while loss < m:
		if low and high and (low[-1] >= high[-1]):
			cur += 1
			loss += low.pop()
		elif len(low) >= 2 and high and (low[-1] < high[-1]):
			if low[-1] + low[-2] >= high[-1]:
				cur += 1
				loss += low.pop()
			elif loss + low[-1] >= m:
				cur += 1
				loss += low.pop()
			else:
				cur += 2
				loss += high.pop()
		elif len(low) == 1 and high and (low[-1] < high[-1]):
			if loss + low[-1] >= m:
				cur += 1
				loss += low.pop()
			else:
				cur += 2
				loss += high.pop()
		elif low:
			cur += 1
			loss += low.pop()
		else:
			cur += 2
			loss += high.pop()
	ret.append(cur)
for r in ret:
	print(r)


import sys
from bisect import bisect_left as bl
input = sys.stdin.readline
for _ in range(int(input())):
	(N, M) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	one = []
	two = []
	for i in range(N):
		if b[i] == 1:
			one.append(a[i])
		else:
			two.append(a[i])
	one.sort(reverse=True)
	two.sort(reverse=True)
	cso = [0] * (len(one) + 1)
	cst = [0] * (len(two) + 1)
	for i in range(len(one)):
		cso[i + 1] = cso[i] + one[i]
	for i in range(len(two)):
		cst[i + 1] = cst[i] + two[i]
	inf = 10 ** 6
	res = inf
	for i in range(len(one) + 1):
		r = M - cso[i]
		if r <= 0:
			res = min(res, i)
		else:
			j = bl(cst, r)
			if j > len(two):
				continue
			res = min(res, i + j * 2)
	if res != inf:
		print(res)
	else:
		print(-1)


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

def f(n, m, a, b):
	imp = []
	reg = []
	for i in range(n):
		if b[i] == 2:
			imp.append(a[i])
		else:
			reg.append(a[i])
	imp.sort(reverse=True)
	reg.sort(reverse=True)
	for i in range(1, len(imp)):
		imp[i] += imp[i - 1]
	for i in range(1, len(reg)):
		reg[i] += reg[i - 1]
	ans = float('inf')
	for i in range(len(imp) + 1):
		res = 0
		cap = 0
		if i > 0:
			cap += imp[i - 1]
		res += 2 * i
		if cap >= m:
			ans = min(ans, res)
		k = bisect.bisect_left(reg, m - cap)
		if k < len(reg):
			ans = min(ans, res + k + 1)
	if ans == float('inf'):
		return -1
	return ans
t = int(input())
result = []
for i in range(t):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	result.append(f(n, m, a, b))
for i in range(t):
	print(result[i])


import sys
from math import inf
from itertools import accumulate
from bisect import bisect_left

def main():
	test_cases = int(sys.stdin.readline())
	for _ in range(test_cases):
		(N, M) = (int(i) for i in sys.stdin.readline().split())
		memory = [int(i) for i in sys.stdin.readline().split()]
		conv = [int(i) for i in sys.stdin.readline().split()]
		singles = []
		doubles = []
		for (m, c) in zip(memory, conv):
			if c == 1:
				singles.append(m)
			else:
				doubles.append(m)
		singles.sort(reverse=True)
		doubles.sort(reverse=True)
		singles_prefix = list(accumulate(singles))
		doubles_prefix = list(accumulate(doubles))
		soln = inf
		j = bisect_left(doubles_prefix, M)
		if j < len(doubles_prefix):
			loss = (j + 1) * 2
			soln = min(soln, loss)
		for (i, s) in enumerate(singles_prefix):
			d = M - s
			loss = i + 1
			if d <= 0:
				soln = min(soln, loss)
			else:
				j = bisect_left(doubles_prefix, d)
				if j < len(doubles_prefix):
					loss += (j + 1) * 2
					soln = min(soln, loss)
		print(-1 if soln == inf else soln)
main()


def find_convenience_lost(n):
	memory = list(map(int, input().split()))[1]
	(memory_per_app, weight) = (list(map(int, input().split())), list(map(int, input().split())))
	ones = list(reversed(sorted([a for (i, a) in enumerate(memory_per_app) if weight[i] == 1])))
	twos = list(reversed(sorted([a for (i, a) in enumerate(memory_per_app) if weight[i] == 2])))
	(i, j) = (0, 0)
	memory_removed = 0
	convenience_points_lost = 0
	while i < len(ones) - 1 and j < len(twos):
		if memory_removed + twos[j] >= memory or memory_removed + ones[i] >= memory:
			return convenience_points_lost + 1 if memory_removed + ones[i] >= memory else convenience_points_lost + 2
		if ones[i] + ones[i + 1] <= twos[j]:
			memory_removed += twos[j]
			convenience_points_lost += 2
			j += 1
		else:
			memory_removed += ones[i]
			convenience_points_lost += 1
			i += 1
	while j < len(twos):
		if memory_removed >= memory:
			return convenience_points_lost
		if i == len(ones) - 1:
			if ones[i] >= twos[j] or ones[i] + memory_removed >= memory:
				memory_removed += ones[i]
				convenience_points_lost += 1
				i += 1
				continue
		memory_removed += twos[j]
		convenience_points_lost += 2
		j += 1
	while i < len(ones):
		if memory_removed >= memory:
			return convenience_points_lost
		memory_removed += ones[i]
		convenience_points_lost += 1
		i += 1
	if memory_removed >= memory:
		return convenience_points_lost
	return -1
n = int(input())
for i in range(n):
	print(find_convenience_lost(i))


rn = lambda : int(input())
rns = lambda : map(int, input().split())
rl = lambda : list(map(int, input().split()))
rs = lambda : input()
YN = lambda x: print('YES') if x else print('NO')
mod = lambda x: x % (10 ** 9 + 7)

def d(a):
	d = {}
	for i in a:
		if i not in d:
			d[i] = 0
		d[i] += 1
	return d
for _ in range(rn()):
	(n, m) = rns()
	a = rl()
	b = rl()
	if sum(a) < m:
		print(-1)
	else:
		ones = []
		twos = []
		for i in range(n):
			if b[i] == 1:
				ones.append(a[i])
			else:
				twos.append(a[i])
		ones.sort(reverse=True)
		twos.sort(reverse=True)
		i = 0
		j = 0
		acc = 0
		while acc < m and i < len(ones):
			acc += ones[i]
			i += 1
		while acc < m and j < len(twos):
			acc += twos[j]
			j += 1
		ans = i + 2 * j
		while i > 0:
			i -= 1
			acc -= ones[i]
			while acc < m and j < len(twos):
				acc += twos[j]
				j += 1
			if acc >= m:
				ans = min(ans, i + 2 * j)
			else:
				break
		print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	memories = list(map(int, input().split()))
	convenience = list(map(int, input().split()))
	(X, Y) = ([], [])
	for (a, b) in zip(memories, convenience):
		if b == 1:
			X.append(a)
		else:
			Y.append(a)
	X.sort(reverse=True)
	Y.sort()
	(i, j) = (0, 0)
	suma = sum(Y)
	puntos = float('inf')
	while i <= len(X):
		while j < len(Y) and suma - Y[j] >= m:
			suma -= Y[j]
			j += 1
		if suma >= m:
			puntos = min(puntos, i + 2 * (len(Y) - j))
		if i < len(X):
			suma += X[i]
		i += 1
	if suma < m:
		print(-1)
		continue
	print(puntos)


from bisect import bisect_left

def solve():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	i = 0
	q = [None, [], []]
	for v in map(int, input().split()):
		q[v].append(a[i])
		i += 1
	aa = q[1]
	bb = q[2]
	aa.sort(reverse=True)
	bb.sort(reverse=True)
	cc = [0] * (len(bb) + 1)
	for i in range(len(bb)):
		cc[i + 1] = cc[i] + bb[i]
	s = m
	z = len(cc)
	ans = int(1000000000.0)
	for i in range(len(aa)):
		idx = bisect_left(cc, s)
		if idx < z:
			ans = min(ans, i + idx * 2)
		s -= aa[i]
	i = len(aa)
	idx = bisect_left(cc, s)
	if idx < z:
		ans = min(ans, i + idx * 2)
	if ans == int(1000000000.0):
		ans = -1
	print(ans)
for i in range(int(input())):
	solve()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().rsplit())
	gen_a = map(int, input().rsplit())
	gen_b = map(int, input().rsplit())
	(a_1, a_2) = ([0], [0])
	total_m = 0
	for (i, j) in zip(gen_a, gen_b):
		if j == 1:
			a_1.append(i)
		else:
			a_2.append(i)
		total_m += i
	if total_m < m:
		print(-1)
		continue
	a_1 = sorted(a_1)
	a_2 = sorted(a_2)
	(sum_m, sum_r) = (0, 0)
	(l, r) = (len(a_1) - 1, len(a_2) - 1)
	while l + r > 0:
		if a_1[l] >= m - sum_m:
			sum_m += a_1[l]
			sum_r += 1
			break
		if a_2[r] >= m - sum_m:
			sum_m += a_2[r]
			sum_r += 2
			break
		if r <= 0 and l > 0:
			sum_m += a_1[l]
			sum_r += 1
			l -= 1
		elif l <= 0 and r > 0:
			sum_m += a_2[r]
			sum_r += 2
			r -= 1
		elif a_1[l] + a_1[l - 1] > a_2[r]:
			sum_m += a_1[l]
			sum_r += 1
			l -= 1
		else:
			sum_m += a_2[r]
			sum_r += 2
			r -= 1
		if sum_m >= m:
			break
	print(sum_r)


import collections, sys, functools, heapq, bisect
input = sys.stdin.readline
mod = 10 ** 9 + 7

def modInverse(a, m):
	m0 = m
	y = 0
	x = 1
	if m == 1:
		return 0
	while a > 1:
		q = a // m
		t = m
		m = a % m
		a = t
		t = y
		y = x - q * y
		x = t
	if x < 0:
		x = x + m0
	return x
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().strip().split())
	a = list(map(int, input().strip().split()))
	b = list(map(int, input().strip().split()))
	a1 = []
	a2 = []
	for (x, i) in zip(a, b):
		if i == 1:
			a1.append(x)
		else:
			a2.append(x)
	a1.sort(reverse=True)
	a2.sort(reverse=True)
	for i in range(1, len(a1)):
		a1[i] += a1[i - 1]
	for i in range(1, len(a2)):
		a2[i] += a2[i - 1]
	if a1 and a2:
		if a1[-1] + a2[-1] < m:
			print(-1)
			continue
	elif a1:
		if a1[-1] < m:
			print(-1)
			continue
	elif a2:
		if a2[-1] < m:
			print(-1)
			continue
	ans = len(a1) + 2 * len(a2)
	if a1:
		y = bisect.bisect_left(a1, m)
		if y < len(a1) and a1[y] >= m:
			ans = min(ans, y + 1)
	if a2:
		y = bisect.bisect_left(a2, m)
		if y < len(a2) and a2[y] >= m:
			ans = min(ans, 2 * (y + 1))
	for i in range(len(a1)):
		x = m - a1[i]
		if x < 0:
			print(ans)
			break
		y = bisect.bisect_left(a2, x)
		if y < len(a2) and a1[i] + a2[y] >= m:
			ans = min(ans, 2 * (y + 1) + (i + 1))
	else:
		print(ans)


from sys import stderr

def dbp(*args, **kwargs):
	pass

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

def do_thing():
	(N, freeme) = get_int_list()
	mlist = get_int_list()
	clist = get_int_list()
	if sum(mlist) < freeme:
		return -1
	c1list = []
	c2list = []
	rsum = 0
	for i in range(N):
		if clist[i] == 1:
			c1list.append(mlist[i])
		else:
			t = mlist[i]
			c2list.append(t)
			rsum += t
	c1list.sort(reverse=True)
	c2list.sort(reverse=True)
	dbp('target:', freeme)
	dbp(c1list)
	dbp(c2list)
	lsum = 0
	r = len(c2list)
	bcc = float('inf')
	for l in range(len(c1list) + 1):
		dbp('before:', l, lsum, r, rsum, bcc)
		while r > 0 and lsum + rsum - c2list[r - 1] >= freeme:
			r -= 1
			rsum -= c2list[r]
		if lsum + rsum >= freeme:
			cost = 2 * r + l
			dbp(l, lsum, r, rsum, 'goodcost:', cost)
			bcc = min(cost, bcc)
		if l < len(c1list):
			lsum += c1list[l]
		dbp('after:', l, lsum, r, rsum, bcc)
	return bcc if bcc != float('inf') else -1
maxcc = int(input().strip())
for cc in range(maxcc):
	print(do_thing())


import sys
import math
from collections import defaultdict, Counter
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')
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	tot = 0
	s1 = []
	s2 = []
	for j in range(n):
		tot += a[j]
		if b[j] == 1:
			s1.append(a[j])
		else:
			s2.append(a[j])
	if tot < m:
		print(-1)
		continue
	s1.sort(reverse=True)
	s2.sort(reverse=True)
	l1 = len(s1)
	l2 = len(s2)
	p = 0
	q = 0
	ans = 0
	cur = 0
	while cur < m:
		if p < l1:
			if s1[p] + cur >= m:
				ans += 1
				break
			if p < l1 - 1:
				if q < l2:
					if s1[p] + s1[p + 1] <= s2[q]:
						ans += 2
						cur += s2[q]
						q += 1
					else:
						ans += 1
						cur += s1[p]
						p += 1
				else:
					while cur < m:
						ans += 1
						cur += s1[p]
						p += 1
					break
			elif s1[p] >= s2[q]:
				ans += 1
				cur += s1[p]
				p += 1
			else:
				cur += s2[q]
				ans += 2
				q += 1
		else:
			while cur < m:
				ans += 2
				cur += s2[q]
				q += 1
			break
	print(ans)


def solve():
	(n, m) = input().split()
	n = int(n)
	m = int(m)
	mem = input().split()
	unit = input().split()
	regular = []
	important = []
	for i in range(n):
		mem[i] = int(mem[i])
		unit[i] = int(unit[i])
		if unit[i] == 1:
			regular.append(mem[i])
		else:
			important.append(mem[i])
	regular.sort(reverse=True)
	important.sort(reverse=True)
	sum_regular = 0
	sum_important = sum(important)
	index_important = len(important)
	res = 1000000000.0 + 1
	for i in range(len(regular) + 1):
		while index_important > 0 and sum_regular + sum_important - important[index_important - 1] >= m:
			index_important -= 1
			sum_important -= important[index_important]
		if sum_regular + sum_important >= m:
			res = min(res, 2 * index_important + i)
		if i != len(regular):
			sum_regular += regular[i]
	if res != 1000000000.0 + 1:
		return res
	else:
		return -1
no_tests = int(input())
results = []
for i in range(no_tests):
	results.append(solve())
for result in results:
	print(result)


import sys
from bisect import *
zz = 1
sys.setrecursionlimit(10 ** 5)
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 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 ii():
	return input().rstrip()

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 gtc(tc, ans):
	print('Case #' + str(tc) + ':', ans)

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()
uu = t
while t > 0:
	t -= 1
	(n, m) = mi()
	a = li()
	b = li()
	d = [[], [], []]
	for i in range(n):
		d[b[i]].append(a[i])
	for i in [1, 2]:
		d[i].sort(reverse=True)
	pre = [0]
	for i in range(len(d[1])):
		pre.append(pre[-1] + d[1][i])
	w = bisect_left(pre, m)
	mini = 10 ** 18 if w == len(pre) else w
	c = 0
	for j in range(len(d[2])):
		c += d[2][j]
		p = m - c
		if p <= 0:
			mini = min(mini, (j + 1) * 2)
		else:
			w = bisect_left(pre, p)
			if w != len(pre):
				mini = min(mini, (j + 1) * 2 + w)
	print(mini if mini < 10 ** 18 else -1)


for t in range(int(input())):
	(n, m) = [int(k) for k in input().split()]
	a = [int(k) for k in input().split()]
	b = [int(k) for k in input().split()]
	if m > sum(a):
		print(-1)
		continue
	imp = []
	non = []
	for i in range(n):
		if b[i] == 2:
			imp += [a[i]]
		else:
			non += [a[i]]
	ans = 0
	imp.sort(reverse=True)
	non.sort(reverse=True)
	il = len(imp)
	nl = len(non)
	ii = 0
	ni = 0
	while m > 0:
		if ni < nl:
			m -= non[ni]
			ni += 1
			ans += 1
		else:
			m -= imp[ii]
			ii += 1
			ans += 2
	fin = ans
	ni -= 1
	while ni >= 0:
		m += non[ni]
		ans -= 1
		ni -= 1
		while m > 0 and ii < il:
			m -= imp[ii]
			ii += 1
			ans += 2
		if m > 0:
			break
		if ans < fin:
			fin = ans
	print(fin)


import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	c = []
	ones = [0]
	for i in range(n):
		c.append((a[i] / b[i], b[i]))
		if b[i] == 1:
			ones.append(a[i])
	ones.sort()
	ones = ones[::-1]
	if max(ones) >= k:
		print(1)
		continue
	if len(ones) == n + 1:
		s = 0
		if sum(ones) < k:
			print(-1)
			continue
		for i in range(n):
			s += ones[i]
			if s >= k:
				print(i + 1)
				break
		continue
	c.sort()
	c = c[::-1]
	d = []
	temp = [c[0]]
	for i in range(n - 1):
		if c[i][0] == c[i + 1][0]:
			temp.append(c[i + 1])
		else:
			d.extend(temp[::-1])
			temp = [c[i + 1]]
	d.extend(temp[::-1])
	c = d
	ans = 0
	temp = 0
	flag = False
	temp_list = []
	x = 0
	for i in range(n):
		if ones[x] >= k - temp:
			ans += 1
			flag = True
			break
		ans += c[i][1]
		temp += c[i][0] * c[i][1]
		if c[i][1] == 1:
			x += 1
		temp_list.append(c[i])
		if temp >= k:
			flag = True
			break
	if not flag:
		print(-1)
		continue
	temp_list = temp_list[::-1]
	for i in range(len(temp_list)):
		if temp - c[i][0] * c[i][1] >= k:
			temp -= c[i][0]
			ans -= c[i][1]
	print(ans)


def dell(mlst, imp, m):
	n = len(mlst)
	cc = []
	for i in range(n):
		cc.append((mlst[i] / imp[i], i))
	cc.sort()
	sm = lose = 0
	i = place2 = place = place1 = -1
	for i in range(n - 1, -1, -1):
		place = cc[i][1]
		sm += mlst[place]
		lose += imp[place]
		if imp[place] == 2:
			place2 = place
		else:
			place1 = place
		if sm >= m:
			break
	if sm < m:
		return -1
	if place == place2:
		if place1 != -1 and sm - mlst[place1] >= m:
			return lose - 1
		i -= 1
		while i >= 0 and imp[cc[i][1]] == 2:
			i -= 1
		if i >= 0 and sm - mlst[place2] + mlst[cc[i][1]] >= m:
			return lose - 1
	return lose
t = int(input())
for u in range(t):
	mm = input().split()
	ml = list(map(int, input().split()))
	imp = list(map(int, input().split()))
	print(dell(ml, imp, int(mm[1])))


import math
import time
from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
import sys
from heapq import heapify, heappush, heappop
MOD = 1000000007
t = int(input())
for _ in range(t):
	(n, m) = map(int, stdin.readline().split())
	a = list(map(int, stdin.readline().split()))
	b = list(map(int, stdin.readline().split()))
	one = []
	two = []
	for i in range(n):
		if b[i] == 1:
			one.append(a[i])
		else:
			two.append(a[i])
	one.sort(reverse=True)
	two.sort(reverse=True)
	ans = 0
	curr = 0
	if sum(a) < m:
		print(-1)
	else:
		preone = [0]
		pretwo = [0]
		for i in one:
			preone.append(preone[-1] + i)
		for i in two:
			pretwo.append(pretwo[-1] + i)
		final = math.inf
		j = 0
		for i in range(len(one), -1, -1):
			temp = preone[i]
			extra = m - temp
			while j <= len(two) and pretwo[j] < extra:
				j += 1
			if j <= len(two) and pretwo[j] >= extra:
				final = min(final, i + j + j)
			else:
				j = len(two)
		print(final)


from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque as dq, Counter as C
from math import factorial as f, ceil, gcd, sqrt, log
from itertools import permutations as p
from bisect import bisect_left as bl, bisect_right as br
from sys import stdin, stdout
input = stdin.readline
mp = lambda : map(int, input().split())
it = lambda : int(input())
ls = lambda : list(input().strip())
lcm = lambda a, b: a * b // gcd(a, b)
mod = 1000000007
for _ in range(it()):
	(a, b) = mp()
	a1 = list(mp())
	b1 = list(mp())
	ones = []
	twos = []
	for i in range(a):
		if b1[i] & 1:
			ones.append(a1[i])
		else:
			twos.append(a1[i])
	tot = len(ones) + 2 * len(twos)
	sm = tot
	ones.sort()
	twos.sort()
	ls1 = 0
	while b > 0:
		if ones and ones[-1] >= b:
			tot -= 1
			ls1 = ones[-1]
			b -= ones.pop()
		elif len(ones) > 1 and len(twos):
			if ones[-1] + ones[-2] > twos[-1]:
				tot -= 2
				ls1 = ones[-2]
				b -= ones.pop() + ones.pop()
			else:
				tot -= 2
				b -= twos.pop()
		elif len(ones) <= 1 and twos:
			tot -= 2
			b -= twos.pop()
		elif len(twos) == 0 and ones:
			tot -= 1
			ls1 = ones[-1]
			b -= ones.pop()
		else:
			break
	if b > 0:
		print(-1)
	else:
		if ls1 <= b * -1 and ls1 > 0:
			tot += 1
		print(sm - tot)


def solve():
	(n, m) = input().split()
	n = int(n)
	m = int(m)
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	regular = []
	important = []
	for i in range(n):
		if b[i] == 1:
			regular.append(a[i])
		else:
			important.append(a[i])
	regular.sort(reverse=True)
	important.sort(reverse=True)
	s_reg = 0
	s_imp = sum(important)
	index_important = len(important)
	res = 1000000000.0 + 1
	for i in range(len(regular) + 1):
		while index_important > 0 and s_reg + s_imp - important[index_important - 1] >= m:
			index_important -= 1
			s_imp -= important[index_important]
		if s_reg + s_imp >= m:
			res = min(res, 2 * index_important + i)
		if i != len(regular):
			s_reg += regular[i]
	if res != 1000000000.0 + 1:
		print(res)
		return
	else:
		print(-1)
		return
for i in range(int(input())):
	solve()


import collections
import string
import math
import copy
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))

def input():
	return sys.stdin.readline().rstrip('\r\n')
mo = 998244353

def exgcd(a, b):
	if not b:
		return (1, 0)
	(y, x) = exgcd(b, a % b)
	y -= a // b * x
	return (x, y)

def getinv(a, m):
	(x, y) = exgcd(a, m)
	return --1 if x == 1 else x % m

def comb(n, b):
	res = 1
	b = min(b, n - b)
	for i in range(b):
		res = res * (n - i) * getinv(i + 1, mo) % mo
	return res % mo

def quickpower(a, n):
	res = 1
	while n:
		if n & 1:
			res = res * a % mo
		n >>= 1
		a = a * a % mo
	return res

def dis(a, b):
	return abs(a[0] - b[0]) + abs(a[1] - b[1])

def getpref(x):
	if x > 1:
		return x * (x - 1) >> 1
	else:
		return 0
t = int(input())
for ti in range(t):
	(n, m) = map(int, input().split())
	l1 = [int(i) for i in input().split()]
	l2 = [int(i) for i in input().split()]
	s1 = []
	s2 = []
	for (i, j) in zip(l1, l2):
		if j == 2:
			s2.append(i)
		else:
			s1.append(i)
	s1.sort()
	s2.sort()
	cur = 0
	loss = 0
	ans = 1145141919810
	idx = 0
	for (ind, i) in enumerate(s1[::-1]):
		cur += i
		loss += 1
	while idx < len(s1) and cur - s1[idx] >= m:
		cur -= s1[idx]
		idx += 1
		loss -= 1
	if cur >= m:
		ans = min(ans, loss)
	while s2:
		cur += s2.pop()
		loss += 2
		while idx < len(s1) and cur - s1[idx] >= m:
			cur -= s1[idx]
			idx += 1
			loss -= 1
		if cur >= m:
			ans = min(ans, loss)
	if ans == 1145141919810:
		print(-1)
	else:
		print(ans)


import sys
from bisect import bisect_left
from itertools import accumulate
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, m) = map(int, input().split())
		A = list(map(int, input().split()))
		B = list(map(int, input().split()))
		one = [0] + list(accumulate(sorted([a for (a, b) in zip(A, B) if b == 1], reverse=True)))
		two = [0] + list(accumulate(sorted([a for (a, b) in zip(A, B) if b == 2], reverse=True)))
		res = f_inf
		for i in range(len(two)):
			diff = m - two[i]
			idx = bisect_left(one, diff)
			if idx < len(one):
				res = min(res, 2 * i + idx)
		print(res if res != f_inf else -1)
resolve()


import sys
import os
import io
from sys import stdin
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop
import math
from bisect import bisect_left, bisect_right
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

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 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(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

def power(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

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	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 countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def si():
	return input()

def prefix_sum(arr):
	r = [0] * (len(arr) + 1)
	for (i, el) in enumerate(arr):
		r[i + 1] = r[i] + el
	return r

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

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

def li():
	return list(map(int, input().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')
t = 1
t = int(input())
for _ in range(t):
	(n, m) = li()
	a = li()
	b = li()
	if sum(a) < m:
		print(-1)
		continue
	l1 = []
	l2 = []
	for i in range(n):
		if b[i] == 1:
			l1.append(a[i])
		else:
			l2.append(a[i])
	l1.sort(reverse=True)
	l2.sort(reverse=True)
	for i in range(1, len(l2)):
		l2[i] += l2[i - 1]
	for i in range(1, len(l1)):
		l1[i] += l1[i - 1]
	l1.append(0)
	l2.append(0)
	l1.sort()
	l2.sort()
	ans = 100000000000000
	s = 0
	q = len(l1)
	qq = len(l2)
	for i in range(q):
		s = l1[i]
		z = bisect_left(l2, m - s)
		if qq != z:
			if s >= m:
				ans = min(ans, i)
			else:
				ans = min(ans, i + 2 * z)
	print(ans)


def solve():
	inp = input().rstrip().split(' ')
	(n, m) = (int(inp[0]), int(inp[1]))
	a_arr = input().rstrip().split(' ')
	b_arr = input().rstrip().split(' ')
	sum_reg = 0
	sum_imp = 0
	reg_apps = []
	imp_apps = []
	for i in range(n):
		if b_arr[i] == '1':
			reg_apps.append(int(a_arr[i]))
			sum_reg += int(a_arr[i])
		else:
			imp_apps.append(int(a_arr[i]))
			sum_imp += int(a_arr[i])
	reg_apps.sort()
	imp_apps.sort()
	if sum_reg + sum_imp < m:
		print(-1)
		return
	tot_removed = 0
	min_points_lost = 0
	while sum_reg < m - tot_removed:
		tot_removed += imp_apps.pop()
		min_points_lost += 2
	while tot_removed < m and len(reg_apps) + len(imp_apps) > 0:
		if len(reg_apps) == 0:
			tot_removed += imp_apps.pop()
			min_points_lost += 2
		elif len(imp_apps) == 0:
			tot_removed += reg_apps.pop()
			min_points_lost += 1
		elif reg_apps[-1] >= imp_apps[-1]:
			tot_removed += reg_apps.pop()
			min_points_lost += 1
		elif tot_removed + reg_apps[-1] >= m:
			tot_removed += reg_apps.pop()
			min_points_lost += 1
		elif len(reg_apps) > 1 and reg_apps[-1] + reg_apps[-2] > imp_apps[-1]:
			tot_removed += reg_apps.pop()
			tot_removed += reg_apps.pop()
			min_points_lost += 2
		else:
			tot_removed += imp_apps.pop()
			min_points_lost += 2
	print(min_points_lost)

def main():
	T = int(input())
	for c in range(T):
		solve()
main()


from os import path
from io import BytesIO, IOBase
import sys
from heapq import heappush, heappop
from functools import cmp_to_key as ctk
from collections import deque, Counter, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

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

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

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

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 998244353
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('0')
file = 1

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

def solve():
	res = []
	for t in range(ii()):
		(n, m) = mi()
		a = li()
		cost = li()
		if m > sum(a):
			res.append('-1')
			continue
		p = [[] for i in range(2)]
		for i in range(n):
			p[cost[i] - 1].append(a[i])
		p[0].sort(reverse=True)
		p[1].sort(reverse=True)
		(n1, n2) = (len(p[0]), len(p[1]))
		for i in range(1, n2):
			p[1][i] += p[1][i - 1]
		ans = n1 + 2 * n2
		if n2 > 0 and p[1][-1] >= m:
			ans = 2 * (bisect_left(p[1], m) + 1)
		x = 0
		for i in range(n1):
			x += p[0][i]
			x1 = m - x
			if x1 <= 0:
				ans = min(ans, i + 1)
				break
			if n2 > 0 and p[1][-1] >= x1:
				idx = bisect_left(p[1], x1)
				ans = min(ans, i + 2 * (idx + 1) + 1)
		res.append(ans)
	for i in res:
		print(i)
if file:
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	else:
		input = sys.stdin.readline
solve()


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	A1 = []
	A2 = []
	for i in range(n):
		if B[i] == 1:
			A1.append(A[i])
		else:
			A2.append(A[i])
	A1.sort(reverse=True)
	A2.sort(reverse=True)
	S1 = [0]
	for a in A1:
		S1.append(S1[-1] + a)
	S2 = [0]
	for a in A2:
		S2.append(S2[-1] + a)
	ANS = 1 << 60
	ind2 = len(S2) - 1
	for i in range(len(S1)):
		s1 = S1[i]
		while s1 + S2[ind2] >= m:
			ANS = min(ANS, i + ind2 * 2)
			if ind2 > 0:
				ind2 -= 1
			else:
				break
	if ANS == 1 << 60:
		print(-1)
	else:
		print(ANS)


in_length = int(input())
final_ouput = []
for i in range(in_length):
	[num_apps, mem_needed] = input().split()
	mem_used = [int(el) for el in input().split()]
	conv_points = input().split()
	big_num = 5000000000
	out = big_num
	low_apps = []
	high_apps = []
	for j in range(int(num_apps)):
		if conv_points[j] == '1':
			low_apps.append(mem_used[j])
		else:
			high_apps.append(mem_used[j])
	low_apps = sorted(low_apps)
	high_apps = sorted(high_apps)
	low_apps.reverse()
	high_apps.reverse()
	acc_sum_low = 0
	acc_sum_high = sum(high_apps)
	high_length = len(high_apps)
	for j in range(len(low_apps) + 1):
		while high_length > 0 and acc_sum_low + acc_sum_high - high_apps[high_length - 1] >= int(mem_needed):
			high_length -= 1
			acc_sum_high -= high_apps[high_length]
		if acc_sum_low + acc_sum_high >= int(mem_needed):
			out = min(out, 2 * high_length + j)
		if j != len(low_apps):
			acc_sum_low += low_apps[j]
	if out == big_num:
		final_ouput.append(-1)
	else:
		final_ouput.append(out)
for out in final_ouput:
	print(out)


import sys
N = int(200000.0 + 5)
sys.setrecursionlimit(N)

def charming():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = list(zip(a, b))
	c.sort(key=lambda x: x[0] / x[1], reverse=True)
	res = 0
	last = 0
	sum = 0
	for i in range(n):
		if sum >= m:
			break
		sum += c[i][0]
		res += c[i][1]
		last = i
	if sum < m:
		print(-1)
		return
	if c[last][1] == 1:
		print(res)
		return
	for i in range(last + 1, n):
		if c[i][1] == 1 and sum - c[last][0] + c[i][0] >= m:
			print(res - 1)
			return
	for i in range(last):
		if c[i][1] == 1 and sum - c[i][0] >= m:
			print(res - 1)
			return
	print(res)
for t in range(int(input())):
	charming()


from sys import stdin
input = stdin.buffer.readline
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	ones = []
	twos = []
	for i in range(n):
		if b[i] == 1:
			ones.append(a[i])
		else:
			twos.append(a[i])
	ones.sort(reverse=True)
	twos.sort(reverse=True)
	x = 0
	for i in range(len(ones)):
		x = x + ones[i]
		ones[i] = x
	x = 0
	for i in range(len(twos)):
		x = x + twos[i]
		twos[i] = x
	s = x
	ans = 10 ** 8
	ones = [0] + ones
	for i in range(len(ones)):
		x = m - ones[i]
		if x <= 0:
			ans = min(ans, i)
			continue
		if x > s:
			continue
		start = 0
		end = len(twos) - 1
		pos = -1
		while start <= end:
			mid = (start + end) // 2
			if twos[mid] >= x:
				pos = mid
				end = mid - 1
			else:
				start = mid + 1
		ans = min(ans, i + (pos + 1) * 2)
	if ans == 10 ** 8:
		print(-1)
	else:
		print(ans)


import sys
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	mem = list(map(int, input().split()))
	cost = list(map(int, input().split()))
	arr1 = []
	arr2 = []
	for i in range(n):
		if cost[i] == 1:
			arr1.append(mem[i])
		else:
			arr2.append(mem[i])
	arr1.sort(reverse=True)
	arr2.sort(reverse=True)
	sumb = sum(arr2)
	suma = 0
	r = len(arr2)
	ans = int(sys.maxsize)
	for i in range(len(arr1) + 1):
		while r > 0 and suma + sumb - arr2[r - 1] >= m:
			r -= 1
			sumb -= arr2[r]
		if suma + sumb >= m:
			ans = min(ans, i + r * 2)
		if i < len(arr1):
			suma += arr1[i]
	if ans < int(sys.maxsize):
		print(ans)
	else:
		print(-1)


import sys
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	(reg, imp) = ([], [])
	for i in range(n):
		if b[i] == 1:
			reg.append(a[i])
		else:
			imp.append(a[i])
	reg.sort(reverse=True)
	imp.sort(reverse=True)
	(reg_len, imp_len) = (len(reg), len(imp))
	r = imp_len
	ans = sys.maxsize
	(curSumA, curSumB) = (0, sum(imp))
	for i in range(reg_len + 1):
		while r > 0 and curSumA + curSumB - imp[r - 1] >= k:
			r -= 1
			curSumB -= imp[r]
		if curSumA + curSumB >= k:
			ans = min(ans, 2 * r + i)
		if i != reg_len:
			curSumA += reg[i]
	print(-1 if ans == sys.maxsize else ans)


from itertools import repeat

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

def num():
	return int(input())

def nfunc(f, n, *args, **kwargs):
	return (f(*args, **kwargs) for _ in repeat(None, n))
t = num()
for _ in repeat(None, t):
	(n, m) = line()
	mems = list(line())
	uses = list(line())
	norms = sorted((mem for (mem, use) in zip(mems, uses) if use == 1))[::-1]
	imps = sorted((mem for (mem, use) in zip(mems, uses) if use == 2))[::-1]
	(nn, ni) = (len(norms), len(imps))
	ans = 0
	(i, j) = (0, 0)
	while m > 0:
		if i < nn - 1 and j < ni:
			if m > norms[i] and norms[i] + norms[i + 1] < imps[j]:
				ans += 2
				m -= imps[j]
				j += 1
			else:
				ans += 1
				m -= norms[i]
				i += 1
		elif i == nn - 1 and j < ni:
			if m > norms[i] and norms[i] < imps[j]:
				ans += 2
				m -= imps[j]
				j += 1
			else:
				ans += 1
				m -= norms[i]
				i += 1
		elif i < nn:
			ans += 1
			m -= norms[i]
			i += 1
		elif j < ni:
			ans += 2
			m -= imps[j]
			j += 1
		else:
			break
	if m > 0:
		print(-1)
	else:
		print(ans)


R = lambda : list(map(int, input().split()))

def bs(a, k):
	l = 0
	r = len(a) - 1
	while l < r:
		m = l + (r - l) // 2
		if a[m] < k:
			l = m + 1
		else:
			r = m
	m = (l + r) // 2
	return m
for _ in range(int(input())):
	(n, m) = R()
	a = R()
	b = R()
	if sum(a) < m:
		print(-1)
		continue
	(reg, imp) = ([], [])
	for i in range(n):
		if b[i] == 1:
			reg.append(a[i])
		else:
			imp.append(a[i])
	reg = sorted(reg)[::-1]
	imp = sorted(imp)[::-1]
	pi = [0]
	for i in range(len(imp)):
		pi.append(pi[-1] + imp[i])
	mr = 0
	mi = bs(pi, m)
	ans = 10 ** 9
	if pi[mi] >= m:
		ans = mi * 2
	for i in range(len(reg)):
		mr += reg[i]
		lef = m - mr
		mi = bs(pi, lef)
		if pi[mi] + mr >= m:
			ans = min(ans, mi * 2 + i + 1)
	print(ans)


for t in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	d = [int(i) for i in input().split()]
	dff = [int(i) for i in input().split()]
	if sum(d) < m:
		print(-1)
		continue
	d1 = [d[i] for i in range(n) if dff[i] == 1]
	d2 = [d[i] for i in range(n) if dff[i] == 2]
	ld1 = len(d1)
	ld2 = len(d2)
	d1.sort(reverse=True)
	d2.sort(reverse=True)
	p1 = 0
	p2 = 0
	ans = 0
	while m > 0:
		if p1 == ld1 - 1:
			while m > d1[p1]:
				ans += 2
				m -= d2[p2]
				p2 += 1
			if m <= 0:
				break
			else:
				ans += 1
				m -= d1[p1]
				break
		opt1 = 0 if p1 >= ld1 - 1 else d1[p1] + d1[p1 + 1]
		opt2 = 0 if p2 == ld2 else d2[p2]
		if opt2 > opt1:
			if opt2 > m:
				break
			ans += 2
			p2 += 1
			m -= opt2
		else:
			if opt1 > m:
				break
			ans += 1
			m -= d1[p1]
			p1 += 1
	if m > 0:
		opt0 = 0 if p1 == ld1 else d1[p1]
		if opt0 >= m:
			ans += 1
		else:
			ans += 2
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	a1 = [10000000000]
	a2 = [10000000000]
	for i in range(n):
		if b[i] == 1:
			a1.append(a[i])
		else:
			a2.append(a[i])
	a1.sort(reverse=True)
	a2.sort(reverse=True)
	a1[0] = 0
	a2[0] = 0
	for i in range(1, len(a1)):
		a1[i] += a1[i - 1]
	am = False
	c = float('inf')
	for i in range(len(a2)):
		if i >= 1:
			a2[i] += a2[i - 1]
		l = -1
		r = len(a1)
		h = m - a2[i]
		while r > l + 1:
			mid = (l + r) // 2
			if h > a1[mid]:
				l = mid
			else:
				r = mid
		if r != len(a1):
			am = True
			c = min(c, 2 * i + r)
	if am:
		print(c)
	else:
		print(-1)


import collections

def solveTestCase():
	(n, m) = [int(i) for i in input().split()]
	mem = [int(i) for i in input().split()]
	val = [int(i) for i in input().split()]
	if sum(mem) < m:
		print(-1)
		return
	l1 = []
	l2 = []
	for i in range(n):
		if val[i] == 1:
			l1.append(mem[i])
		else:
			l2.append(mem[i])
	l1.sort(reverse=True)
	l2.sort(reverse=True)
	i1 = 0
	i2 = 0
	v = 0
	while m > 0:
		left1 = len(l1) - i1
		left2 = len(l2) - i2
		if left1 == 0:
			m -= l2[i2]
			v += 2
			i2 += 1
		elif left2 == 0:
			m -= l1[i1]
			v += 1
			i1 += 1
		elif l1[i1] >= l2[i2] or m <= l1[i1]:
			m -= l1[i1]
			v += 1
			i1 += 1
		elif m <= l2[i2]:
			m -= l2[i2]
			v += 2
			i2 += 1
		elif left1 >= 2 and l1[i1] + l1[i1 + 1] >= l2[i2]:
			m -= l1[i1]
			v += 1
			i1 += 1
		else:
			m -= l2[i2]
			v += 2
			i2 += 1
	print(v)
t = int(input().split()[0])
while t > 0:
	t -= 1
	solveTestCase()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	(X, Y) = ([], [])
	for (a, b) in zip(A, B):
		if b == 1:
			X.append(a)
		else:
			Y.append(a)
	X.sort(reverse=True)
	Y.sort()
	(i, j) = (0, 0)
	cur = sum(Y)
	ans = float('inf')
	while i <= len(X):
		while j < len(Y) and cur - Y[j] >= m:
			cur -= Y[j]
			j += 1
		if cur >= m:
			ans = min(ans, i + (len(Y) - j) * 2)
		if i < len(X):
			cur += X[i]
		i += 1
	print(ans if ans < float('inf') else -1)


from bisect import bisect_left
T = int(input())
ans_ls = [0] * T

def db(*arg):
	print(*arg)
for t in range(T):
	(N, M) = map(int, input().split())
	a_ls = list(map(int, input().split()))
	b_ls = list(map(int, input().split()))
	b1_memories = []
	b2_memories = []
	for i in range(N):
		if b_ls[i] == 1:
			b1_memories.append(a_ls[i])
		else:
			b2_memories.append(a_ls[i])
	b1_memories.sort(reverse=True)
	b2_memories.sort(reverse=True)
	b1_memories_csum = [0] * len(b1_memories)
	now = 0
	for i in range(len(b1_memories)):
		now += b1_memories[i]
		b1_memories_csum[i] = now
	b2_memories_csum = [0] * (len(b2_memories) + 1)
	now = 0
	for i in range(len(b2_memories) + 1):
		b2_memories_csum[i] = now
		if i < len(b2_memories):
			now += b2_memories[i]
	ans = float('inf')
	for (i, b2_csum) in enumerate(b2_memories_csum):
		needed = M - b2_csum
		if needed <= 0:
			ans = min(ans, 2 * i)
			continue
		if len(b1_memories) == 0:
			if needed <= 0:
				ans = min(ans, 2 * i)
			continue
		i_b1 = bisect_left(b1_memories_csum, needed)
		if i_b1 < len(b1_memories):
			now = i_b1 + 2 * i + 1
			ans = min(ans, now)
	ans_ls[t] = ans if ans != float('inf') else -1
for ans in ans_ls:
	print(ans)


import sys, collections, math, itertools, random, bisect
INF = sys.maxsize

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

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

def input():
	return sys.stdin.readline().strip()
mod = int(1000000000.0 + 7)
for _ in range(int(input())):
	(n, m) = get_ints()
	arr = get_array()
	cc = get_array()
	a = []
	b = []
	for i in range(n):
		if cc[i] == 1:
			a.append(arr[i])
		else:
			b.append(arr[i])
	a.sort(reverse=True)
	b.sort(reverse=True)
	curA = 0
	curB = sum(b)
	cnt = INF
	r = len(b)
	for l in range(len(a) + 1):
		while r > 0 and curA + curB - b[r - 1] >= m:
			r -= 1
			curB -= b[r]
		if curA + curB >= m:
			cnt = min(cnt, 2 * r + l)
		if l != len(a):
			curA += a[l]
	print(cnt if cnt != INF else -1)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353

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

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def L():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
try:
	sys.stdin = open('input.txt', 'r')
except:
	pass

def pmat(A):
	for ele in A:
		print(*ele, end='\n')
for _ in range(L()[0]):
	(n, m) = L()
	A = L()
	B = L()
	A1 = []
	A2 = []
	for i in range(n):
		if B[i] == 1:
			A1.append(A[i])
		else:
			A2.append(A[i])
	A1.sort(reverse=True)
	A2.sort(reverse=True)
	pref1 = [0]
	pref2 = [0]
	for ele in A1:
		pref1.append(pref1[-1] + ele)
	for ele in A2:
		pref2.append(pref2[-1] + ele)
	ans = 10 ** 10
	for i in range(len(pref1)):
		y = m - pref1[i]
		z = bl(pref2, y)
		if z == len(pref2):
			continue
		cost = i + 2 * z
		ans = min(ans, cost)
	if ans == 10 ** 10:
		print(-1)
	else:
		print(ans)
endtime = time.time()


def search(arr, key):
	l = 0
	r = len(arr) - 1
	while l <= r:
		m = (l + r) // 2
		if arr[m] >= key:
			r = m - 1
		else:
			l = m + 1
	return l
t = int(input())
while t > 0:
	t -= 1
	(n, m) = map(int, input().strip().split())
	a = list(map(int, input().strip().split()))
	b = list(map(int, input().strip().split()))
	one = []
	two = []
	for i in range(n):
		if b[i] == 1:
			one.append(a[i])
		else:
			two.append(a[i])
	one.sort(reverse=True)
	two.sort(reverse=True)
	for i in range(1, len(one)):
		one[i] += one[i - 1]
	for i in range(1, len(two)):
		two[i] += two[i - 1]
	if len(two) == 0:
		if one[len(one) - 1] >= m:
			print(search(one, m) + 1)
		else:
			print(-1)
	elif len(one) == 0:
		if two[len(two) - 1] >= m:
			print(search(two, m) * 2 + 2)
		else:
			print(-1)
	elif one[len(one) - 1] + two[len(two) - 1] < m:
		print(-1)
	else:
		ans = 1000000000000000000
		if one[len(one) - 1] >= m:
			ans = search(one, m) + 1
		if two[len(two) - 1] >= m:
			ans = min(ans, search(two, m) * 2 + 2)
		for i in range(len(one)):
			if one[i] + two[len(two) - 1] >= m:
				tmp = i + 1
				if one[i] < m:
					tmp += search(two, m - one[i]) * 2 + 2
				else:
					ans = min(ans, tmp)
					break
				ans = min(ans, tmp)
		print(ans)


import re
import sys
exit = sys.exit
from bisect import bisect_left as bsl, bisect_right as bsr
from collections import Counter, defaultdict as ddict, deque
from functools import lru_cache
cache = lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum = enumerate
ri = lambda : int(rln())
ris = lambda : list(map(int, rfs()))
rln = sys.stdin.readline
rl = lambda : rln().rstrip('\n')
rfs = lambda : rln().split()
mod = 1000000007
d4 = [(0, -1), (1, 0), (0, 1), (-1, 0)]
d8 = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
t = ri()
for _ in range(t):
	(n, m) = ris()
	a = ris()
	b = ris()
	(v1, v2) = ([], [])
	tt = 0
	for i in range(n):
		if b[i] == 1:
			v1.append(a[i])
		else:
			v2.append(a[i])
		tt += a[i]
	if tt < m:
		print(-1)
		continue
	n1 = len(v1)
	n2 = len(v2)
	v1.sort(reverse=1)
	v2.sort(reverse=1)
	ans = inf
	tt = sum(v2)
	i = 0
	for j in range(n2, -1, -1):
		while i < n1 and tt < m:
			tt += v1[i]
			i += 1
		if tt >= m:
			ans = min(ans, 2 * j + i)
		if j > 0:
			tt -= v2[j - 1]
	print(ans)


import bisect
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l1 = sorted([a[i] for i in range(n) if b[i] == 1], reverse=True)
	l2 = sorted([a[i] for i in range(n) if b[i] == 2], reverse=True)
	pre1 = [0]
	pre2 = []
	t1 = 0
	t2 = 0
	for i in range(0, len(l1)):
		t1 += l1[i]
		pre1.append(t1)
	for i in range(0, len(l2)):
		t2 += l2[i]
		pre2.append(t2)
	ans = 10000000000
	for i in range(len(pre1)):
		l = i
		num = m - pre1[i]
		if num > 0:
			ind = bisect.bisect_left(pre2, num)
			if ind == len(l2):
				continue
			l += 2 * (ind + 1)
		ans = min(l, ans)
	if ans == 10000000000:
		print('-1')
	else:
		print(ans)


from os import path
import sys, time
mod = int(1000000000.0 + 7)
from math import ceil, floor, gcd, log, log2, factorial
from collections import defaultdict, Counter, OrderedDict, deque
from itertools import combinations, permutations, accumulate
from bisect import *
from functools import reduce
from operator import mul
maxx = float('inf')
I = lambda : int(sys.stdin.buffer.readline())
tup = lambda : map(int, sys.stdin.buffer.readline().split())
lint = lambda : [int(x) for x in sys.stdin.buffer.readline().split()]
S = lambda : sys.stdin.readline().strip('\n')
grid = lambda r: [lint() for i in range(r)]
stpr = lambda x: sys.stdout.write(f'{x}' + '\n')
star = lambda x: print(' '.join(map(str, x)))
localsys = 0
start_time = time.time()
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
for _ in range(I()):
	(n, m) = tup()
	(A, B) = (lint(), lint())
	(o, t) = ([], [])
	for (i, j) in zip(A, B):
		if j == 1:
			o.append(i)
		else:
			t.append(i)
	o.sort(reverse=True)
	t.sort()
	(i, j, ans, curB) = (0, 0, maxx, sum(t))
	while i <= len(o):
		while j < len(t) and curB - t[j] >= m:
			curB -= t[j]
			j += 1
		if curB >= m:
			ans = min(ans, i + 2 * (len(t) - j))
		if i < len(o):
			curB += o[i]
		i += 1
	print(ans if ans != maxx else -1)
if localsys:
	print('\n\nTime Elased :', time.time() - start_time, 'seconds')


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	(a, b) = (list(map(int, input().split())), list(map(int, input().split())))
	imp = sorted([a[i] for i in range(n) if b[i] == 2])
	not_imp = sorted([a[i] for i in range(n) if b[i] == 1])
	res = 0
	while (imp and not_imp) and m > 0:
		if imp[-1] > sum(not_imp[-2:]) and not_imp[-1] < m:
			m -= imp.pop()
			res += 2
		else:
			m -= not_imp.pop()
			res += 1
	if m > 0:
		while imp and m > 0:
			m -= imp.pop()
			res += 2
		while not_imp and m > 0:
			m -= not_imp.pop()
			res += 1
	if m > 0:
		print(-1)
	else:
		print(res)


import bisect
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	one = []
	two = []
	if sum(a) >= m:
		for i in range(n):
			if b[i] == 1:
				one.append(a[i])
			else:
				two.append(a[i])
		one.sort(reverse=True)
		two.sort(reverse=True)
		pr1 = [0]
		pr2 = [0]
		ans = 3 * n
		for i in one:
			pr1.append(pr1[-1] + i)
		for i in two:
			pr2.append(pr2[-1] + i)
		for i in range(len(pr1)):
			c = bisect.bisect_left(pr2, m - pr1[i])
			if c >= len(pr2):
				c = c - 1
			if pr1[i] + pr2[c] >= m:
				ans = min(ans, i + 2 * c)
		print(ans)
	else:
		print(-1)


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 S():
	return input().strip()

def print_list(l):
	print(' '.join(map(str, l)))
for _ in range(N()):
	(n, m) = RL()
	(a, b) = (RLL(), RLL())
	(l1, l2) = ([], [])
	for i in range(n):
		if b[i] == 1:
			l1.append(a[i])
		else:
			l2.append(a[i])
	l1.sort(reverse=True)
	l2.sort(reverse=True)
	(n1, n2) = (len(l1), len(l2))
	s = sum(l1)
	k2 = 0
	ans = n * 2 + 1
	for k1 in range(n1, -1, -1):
		while s < m and k2 < n2:
			s += l2[k2]
			k2 += 1
		if s < m:
			break
		ans = min(ans, k1 + k2 * 2)
		if k1 > 0:
			s -= l1[k1 - 1]
	print(ans if ans <= n * 2 else -1)


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 bisect import bisect_left as bsl

def main():
	for j in range(int(input())):
		(n, m) = map(int, input().split())
		vals = list(map(int, input().split()))
		imp = list(map(int, input().split()))
		one = []
		two = []
		for s in range(n):
			if imp[s] == 1:
				one.append(vals[s])
			else:
				two.append(vals[s])
		one.sort(reverse=True)
		two.sort(reverse=True)
		if len(two):
			csum = [two[0]]
			for s in range(1, len(two)):
				csum.append(csum[-1] + two[s])
		minsofar = 10 ** 15
		mem = 0
		for s in range(len(one)):
			conv = s + 1
			mem += one[s]
			if mem >= m:
				minsofar = min(minsofar, conv)
			elif len(two):
				ind = min(bsl(csum, m - mem), len(two) - 1)
				if mem + csum[ind] >= m:
					minsofar = min(minsofar, conv + 2 * (ind + 1))
		if len(two) > 0:
			ind = min(bsl(csum, m), len(two) - 1)
			if csum[ind] >= m:
				minsofar = min(minsofar, 2 * (ind + 1))
		if minsofar != 10 ** 15:
			print(minsofar)
		else:
			print(-1)
main()


import math
inf = float('inf')
from collections import defaultdict
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	brr = list(map(int, input().split()))
	a = []
	b = []
	for i in range(n):
		if brr[i] == 1:
			a.append(arr[i])
		else:
			b.append(arr[i])
	a.sort(reverse=True)
	b.sort(reverse=True)
	currSumA = 0
	r = len(b)
	currSumB = sum(b)
	ans = inf
	for l in range(len(a) + 1):
		while r > 0 and currSumA + currSumB - b[r - 1] >= m:
			r -= 1
			currSumB -= b[r]
		if currSumB + currSumA >= m:
			ans = min(ans, 2 * r + l)
		if l != len(a):
			currSumA += a[l]
	if ans == inf:
		print(-1)
	else:
		print(ans)


for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	memories = list(map(int, input().split()))
	points = list(map(int, input().split()))
	if sum(memories) < m:
		print(-1)
	else:
		ones = []
		twos = []
		for i in range(n):
			if points[i] == 1:
				ones.append(memories[i])
			else:
				twos.append(memories[i])
		ones.sort(reverse=True)
		twos.sort(reverse=True)
		a = len(ones)
		b = len(twos)
		(i, j) = (0, 0)
		space = 0
		ans = 0
		while space < m:
			if i < a:
				space += ones[i]
				i += 1
				ans += 1
			else:
				space += twos[j]
				j += 1
				ans += 2
		flag = True
		res = ans
		i -= 1
		while i >= 0:
			ans -= 1
			space -= ones[i]
			i -= 1
			while j < b and space < m:
				space += twos[j]
				j += 1
				ans += 2
			if space < m:
				flag = False
				break
			if ans < res:
				res = ans
		print(res)


def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		d = {'1': [], '2': []}
		for (a, b) in zip(map(int, input().split()), input().split()):
			d[b].append(a)
		if sum(map(sum, d.values())) < m:
			print(-1)
			continue
		(i, j, k, best) = (0, 0, len(d['1']), 1000000)
		ri = [*sorted(d['1']), *sorted(d['2'], reverse=True)]
		while i < n:
			while i < n and m > 0:
				m -= ri[i]
				i += 1
			if m <= 0:
				while m + ri[j] <= 0:
					m += ri[j]
					j += 1
				x = (i if i < k else i * 2 - k) - (j if j < k else j * 2 - k)
				if best > x:
					best = x
			m += ri[j]
			j += 1
		print(best)
main()


import sys
input = sys.stdin.readline
from collections import *
from bisect import *
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	one = []
	two = []
	for i in range(n):
		if b[i] == 1:
			one.append(a[i])
		else:
			two.append(a[i])
	one.sort(reverse=True)
	two.sort(reverse=True)
	one_acc = [0]
	two_acc = [0]
	for o in one:
		one_acc.append(one_acc[-1] + o)
	for t in two:
		two_acc.append(two_acc[-1] + t)
	ans = 10 ** 18
	for i in range(len(one) + 1):
		idx = bisect_left(two_acc, m - one_acc[i])
		if idx == len(two) + 1:
			continue
		ans = min(ans, i + 2 * idx)
	if ans == 10 ** 18:
		print(-1)
	else:
		print(ans)


def solve(a, b, m):
	s = 0
	while m > 0 and a and b:
		if a[-1] >= m:
			m -= a.pop()
			s += 1
			break
		elif len(a) == 1 or b[-1] > a[-1] + a[-2]:
			m -= b.pop()
			s += 2
		else:
			s += 1
			m -= a.pop()
	while m > 0 and a:
		s += 1
		m -= a.pop()
	while m > 0 and b:
		s += 2
		m -= b.pop()
	if m <= 0:
		print(s)
	else:
		print(-1)
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	u = list(map(int, input().split()))
	v = list(map(int, input().split()))
	(a, b) = ([], [])
	for i in range(n):
		if v[i] == 1:
			a.append(u[i])
		else:
			b.append(u[i])
	solve(sorted(a), sorted(b), m)


tests = int(input())
while tests > 0:
	(apps, clean) = list(map(int, input().split()))
	storage = list(map(int, input().split()))
	conv = list(map(int, input().split()))
	if sum(storage) < clean:
		print(-1)
		tests -= 1
		continue
	arr1 = list()
	arr2 = list()
	for i in range(apps):
		if conv[i] == 1:
			arr1.append(storage[i])
		else:
			arr2.append(storage[i])
	arr1.sort(reverse=True)
	arr2.sort(reverse=True)
	if clean in arr1:
		print(1)
		tests -= 1
		continue
	else:
		index1 = 0
		index2 = 0
		convenience = 0
		while clean > 0:
			if index1 < len(arr1) and arr1[index1] >= clean:
				convenience += 1
				break
			state1 = 0
			state2 = 0
			if index1 < len(arr1):
				state1 = arr1[index1]
			if index2 < len(arr2):
				state2 = arr2[index2]
			if index1 < len(arr1) - 1:
				state1 += arr1[index1 + 1]
			if state2 > state1:
				clean -= state2
				index2 += 1
				convenience += 2
			else:
				clean -= arr1[index1]
				index1 += 1
				convenience += 1
		print(convenience)
	tests -= 1


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 bisect import bisect_left as bl
for t in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l1 = []
	l2 = []
	for i in range(n):
		if b[i] == 1:
			l1.append(a[i])
		else:
			l2.append(a[i])
	l1.sort(reverse=True)
	l2.sort(reverse=True)
	l3 = []
	c = 0
	for i in l2:
		c += i
		l3.append(c)
	if sum(l1) + c < m:
		print(-1)
		continue
	c = 0
	x = bl(l3, m)
	if x != len(l3):
		ans = 2 * (x + 1)
	else:
		ans = 2 * len(l3) + len(l1)
	for i in range(len(l1)):
		c += l1[i]
		if c >= m:
			ans = min(ans, i + 1)
		x = bl(l3, m - c)
		if x != len(l3):
			ans = min(ans, 2 * (x + 1) + i + 1)
	print(ans)


import sys, getpass
import math, random
import functools, itertools, collections, heapq, bisect
from collections import Counter, defaultdict, deque
input = sys.stdin.readline
M9 = 10 ** 9 + 7
MAXINT = sys.maxsize
OFFLINE_TEST = getpass.getuser() == 'hkmac'

def log(*args):
	if OFFLINE_TEST:
		print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)

def solve(*args):
	if OFFLINE_TEST:
		log('----- solving ------')
		log(*args)
		log('----- ------- ------')
	return solve_(*args)

def read_matrix(rows):
	return [list(map(int, input().split())) for _ in range(rows)]

def read_strings(rows):
	return [input().strip() for _ in range(rows)]

def solve_(arr, brr, c):
	sumarr = sum(arr)
	if sumarr < c:
		return -1
	if sum(arr) == c:
		return sum(brr)
	order = sorted([(a / b, b, a) for (a, b) in zip(arr, brr)])[::-1]
	log(order)
	mem = 0
	cost = 0
	limit_single = 0
	limit_double = 0
	max_single = False
	max_double = False
	for (_, b, a) in order:
		mem += a
		cost += b
		if b == 1:
			max_single = True
			limit_single += 1
		else:
			limit_double += 1
			max_double = True
		if mem >= c:
			break
	limit_single -= 1
	limit_double -= 1
	res = cost
	log(cost)
	if max_single:
		num_single = 0
		mem = 0
		cost = 0
		for (_, b, a) in order:
			log(num_single, limit_single)
			if b == 1:
				if num_single == limit_single:
					continue
				num_single += 1
			mem += a
			cost += b
			if mem >= c:
				res = min(res, cost)
				break
		else:
			pass
	if max_double:
		num_double = 0
		mem = 0
		cost = 0
		for (_, b, a) in order:
			log(num_double, limit_double)
			if b == 2:
				if num_double == limit_double:
					continue
				num_double += 1
			mem += a
			cost += b
			if mem >= c:
				res = min(res, cost)
				break
		else:
			pass
	return res
all_res = []
for case_num in range(int(input())):
	(_, c) = list(map(int, input().split()))
	arr = list(map(int, input().split()))
	brr = list(map(int, input().split()))
	res = solve(arr, brr, c)
	all_res.append(res)
print('\n'.join((str(r) for r in all_res)))


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
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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 ** 51, func=lambda a, b: 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
for ik in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	if sum(a) < m:
		print(-1)
		continue
	one = []
	two = []
	for i in range(n):
		if b[i] == 1:
			one.append(a[i])
		else:
			two.append(a[i])
	one.sort(reverse=True)
	two.sort(reverse=True)
	w = [0] * (len(one) + 1)
	w1 = [0] * (len(two) + 1)
	for i in range(1, len(one) + 1):
		w[i] += w[i - 1] + one[i - 1]
	for i in range(1, len(two) + 1):
		w1[i] += w1[i - 1] + two[i - 1]

	def find(x):
		for i in range(x + 1):
			left = (x - i) // 2
			if i >= len(w) or left >= len(w1):
				continue
			if w[i] + w1[left] >= m:
				return True
		return False
	st = 0
	end = 2 * len(two) + len(one)
	ans = end
	while st <= end:
		mid = (st + end) // 2
		if find(mid) == True:
			f = 1
			ans = mid
			end = mid - 1
		else:
			st = mid + 1
	print(ans)


import io
import os
from bisect import bisect_left

def solve1(N, M, A, B):
	inf = float('inf')
	best = inf
	for mask in range(1 << N):
		total = 0
		cost = 0
		for pos in range(N):
			if 1 << pos & mask:
				total += A[pos]
				cost += B[pos]
		if total >= M:
			best = min(best, cost)
	if best == inf:
		return -1
	return best

def solve(N, M, A, B):
	A1 = []
	A2 = []
	for (a, b) in zip(A, B):
		if b == 1:
			A1.append(a)
		else:
			A2.append(a)
	A1.sort(reverse=True)
	A2.sort(reverse=True)
	total1 = sum(A1)
	total2 = sum(A2)
	if total1 + total2 < M:
		return -1
	pref1 = [0]
	for x in A1:
		pref1.append(pref1[-1] + x)
	pref2 = [0]
	for x in A2:
		pref2.append(pref2[-1] + x)
	best = float('inf')
	for i in range(len(A1) + 1):
		if pref1[i] >= M:
			best = min(best, i)
	for i in range(len(A2) + 1):
		if pref2[i] >= M:
			best = min(best, 2 * i)
	for i in range(len(A1) + 1):
		target = M - pref1[i]
		if target >= 0:
			index = bisect_left(pref2, target)
			if index < len(pref2):
				assert pref1[i] + pref2[index] >= M
				cost = i + 2 * index
				best = min(best, cost)
	return best
DEBUG = False
if DEBUG:
	import random
	random.seed(0)
	for _ in range(1000):
		N = random.randint(1, 10)
		M = random.randint(1, 10)
		A = [random.randint(1, 10) for i in range(N)]
		B = [random.randint(1, 2) for i in range(N)]
		print('tc', _, N, A, B)
		ans1 = solve1(N, M, A, B)
		ans = solve(N, M, A, B)
		assert ans1 == ans
		print(ans1)
	exit()
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
	(N, M) = [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, M, A, B)
	print(ans)


from collections import Counter
from math import factorial as fac
import bisect
mod = 10 ** 9 + 7
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr1 = list(map(int, input().split()))
	arr2 = list(map(int, input().split()))
	s1 = []
	s2 = []
	ans = 10 ** 20
	for i in range(n):
		if arr2[i] == 2:
			s2.append(arr1[i])
		else:
			s1.append(arr1[i])
	s1.sort(reverse=True)
	s2.sort(reverse=True)
	s1 = [0] + s1
	s2 = [0] + s2
	for i in range(1, len(s1)):
		s1[i] += s1[i - 1]
	for i in range(1, len(s2)):
		s2[i] += s2[i - 1]
	for i in range(len(s1)):
		c = m - s1[i]
		bi = bisect.bisect_left(s2, c)
		if bi != len(s2):
			ans = min(ans, i + 2 * bi)
	if ans == 10 ** 20:
		print(-1)
	else:
		print(ans)


def solve():
	(n, m) = map(int, input().split())
	A = [int(i) for i in input().split()]
	B = [int(i) for i in input().split()]
	one = []
	two = []
	for i in range(n):
		(a, b) = (A[i], B[i])
		if b == 1:
			one.append(a)
		else:
			two.append(a)
	one = [0] + sorted(one, reverse=True)
	two = [0] + sorted(two, reverse=True)
	ln1 = len(one)
	ln2 = len(two)
	for i in range(1, ln1):
		one[i] += one[i - 1]
	for i in range(1, ln2):
		two[i] += two[i - 1]
	j = 0
	INF = float('INF')
	ans = INF
	for i in range(ln1)[::-1]:
		while j < ln2 and m > one[i] + two[j]:
			j += 1
		if j == ln2:
			break
		ans = min(ans, i + j * 2)
	print(ans if ans < INF else -1)
t = int(input())
for _ in range(t):
	solve()


from sys import stdin
nii = lambda : map(int, stdin.readline().split())
lnii = lambda : list(map(int, stdin.readline().split()))
from itertools import accumulate
from bisect import *
t = int(input())
for tt in range(t):
	(n, m) = nii()
	a = lnii()
	b = lnii()
	if sum(a) < m:
		print(-1)
		continue
	b1 = []
	b2 = []
	for (aa, bb) in zip(a, b):
		if bb == 1:
			b1.append(aa)
		else:
			b2.append(aa)
	b1.sort(reverse=True)
	b2.sort(reverse=True)
	b1 = [0] + list(accumulate(b1))
	b2 = [0] + list(accumulate(b2))
	ans = 10 ** 18
	for i in range(len(b1)):
		zan = m - b1[i]
		if zan <= 0:
			ans = min(ans, i)
			break
		inx = bisect_left(b2, zan)
		if inx != len(b2):
			ans = min(ans, i + inx * 2)
	print(ans)