Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.

The exam consists of $n$ problems that can be solved in $T$ minutes. Thus, the exam begins at time $0$ and ends at time $T$. Petya can leave the exam at any integer time from $0$ to $T$, inclusive.

All problems are divided into two types:   easy problems — Petya takes exactly $a$ minutes to solve any easy problem;  hard problems — Petya takes exactly $b$ minutes ($b > a$) to solve any hard problem. 

Thus, if Petya starts solving an easy problem at time $x$, then it will be solved at time $x+a$. Similarly, if at a time $x$ Petya starts to solve a hard problem, then it will be solved at time $x+b$.

For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $t_i$ ($0 \le t_i \le T$) at which it will become mandatory (required). If Petya leaves the exam at time $s$ and there is such a problem $i$ that $t_i \le s$ and he didn't solve it, then he will receive $0$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $t_i \le s$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $s$ Petya can have both "mandatory" and "non-mandatory" problems solved.

For example, if $n=2$, $T=5$, $a=2$, $b=3$, the first problem is hard and $t_1=3$ and the second problem is easy and $t_2=2$. Then:  if he leaves at time $s=0$, then he will receive $0$ points since he will not have time to solve any problems;  if he leaves at time $s=1$, he will receive $0$ points since he will not have time to solve any problems;  if he leaves at time $s=2$, then he can get a $1$ point by solving the problem with the number $2$ (it must be solved in the range from $0$ to $2$);  if he leaves at time $s=3$, then he will receive $0$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them;  if he leaves at time $s=4$, then he will receive $0$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them;  if he leaves at time $s=5$, then he can get $2$ points by solving all problems. 

Thus, the answer to this test is $2$.

Help Petya to determine the maximal number of points that he can receive, before leaving the exam.


-----Input-----

The first line contains the integer $m$ ($1 \le m \le 10^4$) — the number of test cases in the test.

The next lines contain a description of $m$ test cases. 

The first line of each test case contains four integers $n, T, a, b$ ($2 \le n \le 2\cdot10^5$, $1 \le T \le 10^9$, $1 \le a < b \le 10^9$) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively.

The second line of each test case contains $n$ numbers $0$ or $1$, separated by single space: the $i$-th number means the type of the $i$-th problem. A value of $0$ means that the problem is easy, and a value of $1$ that the problem is hard.

The third line of each test case contains $n$ integers $t_i$ ($0 \le t_i \le T$), where the $i$-th number means the time at which the $i$-th problem will become mandatory.

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


-----Output-----

Print the answers to $m$ test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam.


-----Example-----
Input
10
3 5 1 3
0 0 1
2 1 4
2 5 2 3
1 0
3 2
1 20 2 4
0
16
6 20 2 5
1 1 0 1 0 0
0 8 2 9 11 6
4 16 3 6
1 0 1 1
8 3 5 6
6 20 3 6
0 1 0 0 1 0
20 11 3 20 16 17
7 17 1 6
1 1 0 1 0 0 0
1 7 0 11 10 15 10
6 17 2 6
0 0 1 0 0 1
7 6 3 7 10 12
5 17 2 5
1 1 1 1 0
17 11 10 6 4
1 1 1 2
0
1

Output
3
2
1
0
1
4
0
1
2
1

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Sorting

Amortized analysis

Greedy algorithms


Solutions:
num_tests = int(input())
for test in range(num_tests):
	inp = input().rstrip().split(' ')
	n = int(inp[0])
	T = int(inp[1])
	a = int(inp[2])
	b = int(inp[3])
	inp = input().rstrip().split(' ')
	difficulty = [int(inp[i]) for i in range(len(inp))]
	inp = input().rstrip().split(' ')
	mandatory_at = [int(inp[i]) for i in range(len(inp))]
	joint = list(zip(mandatory_at, difficulty))
	joint.sort(key=lambda tup: tup[1])
	joint.sort(key=lambda tup: tup[0])
	num_hard = sum(difficulty)
	num_easy = n - num_hard
	scores = []
	mandatory_score = 0
	mandatory_time = 0
	for (time, difficulty) in joint:
		left_time = time - 1 - mandatory_time
		if left_time >= 0:
			score = mandatory_score
			if int(left_time / a) <= num_easy:
				score += int(left_time / a)
			else:
				score += num_easy
				left_time -= num_easy * a
				score += min(int(left_time / b), num_hard)
			scores.append(score)
		else:
			scores.append(0)
		mandatory_time += difficulty * (b - a) + a
		mandatory_score += 1
		num_easy = num_easy - (1 - difficulty)
		num_hard = num_hard - difficulty
	left_time = T - mandatory_time
	if left_time >= 0:
		score = mandatory_score
		if int(left_time / a) <= num_easy:
			score += int(left_time / a)
		else:
			score += num_easy
			left_time -= num_easy * a
			score += min(int(left_time / b), num_hard)
		scores.append(score)
	else:
		scores.append(0)
	print(max(scores))


from sys import stdin, stdout
m = int(stdin.readline().strip())
for _ in range(m):
	(n, T, a, b) = map(int, stdin.readline().split())
	diff = list(map(int, stdin.readline().split()))
	mand = list(map(int, stdin.readline().split()))
	(easy, hard) = ([], [])
	for i in range(n):
		if diff[i]:
			hard.append(mand[i])
		else:
			easy.append(mand[i])
	easy.sort()
	hard.sort()
	(t, i, j, k) = (0, 0, 0, 0)
	ans = 0
	while t < T:
		(_be, _bh) = (i < len(easy), j < len(hard))
		if _be and _bh:
			if t < hard[j]:
				if t < easy[i]:
					ans = max(ans, i + j)
					_t = t + b
					if _t <= T and (j + 1 == len(hard) or _t < hard[j + 1]) and (_t < easy[i]):
						k = i
				t += a
				i += 1
			else:
				t = t + b - a * (i - k)
				j += 1
				i = k
		elif _be:
			if t < easy[i]:
				ans = max(ans, i + j)
			i += 1
			t += a
		elif _bh:
			if t < hard[j]:
				ans = max(ans, i + j)
			j += 1
			t = t + b - a * (i - k)
			i = k
		else:
			break
	if t <= T and (i == len(easy) or t < easy[i]) and (j == len(hard) or t < hard[j]):
		ans = max(ans, i + j)
	stdout.write('{}\n'.format(ans))


from sys import stdin
from bisect import bisect_right as leqcount

def input():
	return stdin.readline()[:-1]

def intput():
	return int(input())

def sinput():
	return input().split()

def intsput():
	return map(int, sinput())
debugging = 0

def dprint(*args):
	if debugging:
		print(*args)
	else:
		pass
m = intput()
for _ in range(m):
	(n, T, a, b) = intsput()
	ishard = list(intsput())
	ti = list(intsput())
	easy = []
	hard = []
	for i in range(n):
		if ishard[i]:
			hard.append(ti[i])
		else:
			easy.append(ti[i])
	ti.sort()
	easy.sort()
	hard.sort()
	dprint(T)
	dprint(a, b)
	dprint(easy, hard)
	dprint()
	best = 0
	table = {}
	searchset = set(ti)
	searchset.add(T)
	for limitseed in searchset:
		for limit in (limitseed, limitseed - 1):
			easycnt = leqcount(easy, limit)
			hardcnt = leqcount(hard, limit)
			reqtime = easycnt * a + hardcnt * b
			if reqtime <= limit:
				sqeeze = min((limit - reqtime) // a, len(easy) - easycnt)
				easycnt += sqeeze
				reqtime += sqeeze * a
				sqeeze = min((limit - reqtime) // b, len(hard) - hardcnt)
				hardcnt += sqeeze
				reqtime += sqeeze * b
				table[limit] = easycnt + hardcnt
				best = max(best, table[limit])
				dprint(limit, ':', table[limit], '(', reqtime, ')')
	print(best)
	dprint()


import sys, math
MOD = 10 ** 9 + 7

def max_points(time, easy_req, hard_req):
	if easy_req * a + hard_req * b > time or time < 0 or time > t:
		return 0
	else:
		time -= easy_req * a + hard_req * b
	ans = easy_req + hard_req
	ans += min(easy - easy_req, time // a)
	time -= a * min(easy - easy_req, time // a)
	ans += min(hard - hard_req, time // b)
	return ans
for _ in range(int(input())):
	(n, t, a, b) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	easy = x.count(0)
	hard = n - easy
	ans = max_points(t, easy, hard)
	req = {ys: [0, 0] for ys in y}
	req[0] = [0, 0]
	for i in range(n):
		req[y[i]][x[i]] += 1
	times = sorted(req.keys())
	for i in range(1, len(times)):
		req[times[i]][0] += req[times[i - 1]][0]
		req[times[i]][1] += req[times[i - 1]][1]
	for i in range(1, len(times)):
		req[times[i] - 1] = req[times[i - 1]][:]
	for time in req:
		ans = max(ans, max_points(time, req[time][0], req[time][1]))
	print(ans)


from math import *
import os, sys
from io import BytesIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
sys.setrecursionlimit(10 ** 9)

def koll(ca, cb, t, ga, gb, a, b):
	t -= ca * a + cb * b
	cx = min(ga - ca, t // a)
	t -= cx * a
	cx += min(gb - cb, t // b)
	return max(cx, 0)
for i in range(min(10 ** 18, int(input()))):
	(n, ct, a, b) = map(int, input().split())
	m = list(map(int, input().split()))
	t = list(map(int, input().split()))
	cur = {}
	s = set()
	ga = 0
	gb = 0
	for i in range(n):
		if m[i] == 0:
			ga += 1
		else:
			gb += 1
		if t[i] not in cur:
			cur[t[i]] = [0, 0]
		cur[t[i]][m[i]] += 1
		s.add(t[i])
	s = sorted(s)
	end = [0] * (len(s) + 1)
	lol = set()
	ca = 0
	cb = 0
	for i in range(len(s) - 1):
		ca += cur[s[i]][0]
		cb += cur[s[i]][1]
		if ca * a + cb * b < s[i + 1]:
			lol.add(s[i])
		end[i + 1] = ca * a + cb * b
	i = len(s) - 1
	ca += cur[s[i]][0]
	cb += cur[s[i]][1]
	end[i + 1] = ca * a + cb * b
	lol.add(s[-1])
	s.append(ct + 1)
	ca = 0
	cb = 0
	mx = koll(0, 0, min(ct, max(s[0] - 1, 0)), ga, gb, a, b)
	for i in range(len(s) - 1):
		ca += cur[s[i]][0]
		cb += cur[s[i]][1]
		if s[i] in lol and end[i + 1] <= ct:
			mx = max(mx, ca + cb + koll(ca, cb, s[i + 1] - 1, ga, gb, a, b))
	print(mx)


import math
tv = int(input())
for _ in range(tv):
	(n, t, a, b) = map(int, input().split())
	A = [*map(int, input().split())]
	dif = sum(A)
	ez = n - dif
	T = sorted([[j - 1, i] for (i, j) in enumerate([*map(int, input().split())])])
	T.append([t, -1])
	dif_need = 0
	ez_need = 0
	res = 0
	for i in range(len(T)):
		if dif_need * b + ez_need * a <= T[i][0]:
			t_rest = T[i][0] - dif_need * b - ez_need * a
			ez_r = min(math.floor(t_rest / a), ez - ez_need)
			t_rest -= ez_r * a
			dif_r = min(math.floor(t_rest / b), dif - dif_need)
			t_rest -= dif_r * b
			res = max(res, dif_need + ez_need + dif_r + ez_r)
		if T[i][1] != -1:
			dif_need += A[T[i][1]]
			ez_need += not A[T[i][1]]
	print(res)


import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	(n, T, a, b) = map(int, input().split())
	level = [int(i) for i in input().split()]
	time = [int(i) for i in input().split()]
	diff = zip(time, level)
	diff = sorted(diff)
	easy = level.count(0)
	hard = n - easy
	if easy * a + hard * b <= T:
		print(n)
	else:
		time = 0
		question = 0
		last = 0
		hard1 = 0
		for i in range(len(diff)):
			if diff[i][0] > time:
				question = max(last, question)
				new_time = (diff[i][0] - 1 - time) // a
				new_time = min(new_time, easy)
				question = max(question, new_time + last)
			if diff[i][1] == 0:
				time += a
				easy -= 1
				last += 1
			elif diff[i][1] == 1:
				time += b
				last += 1
		print(question)


import sys

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

def slv():
	(n, T, a, b) = map(int, input().split())
	problem_type = list(map(int, input().split()))
	reqtime = list(map(int, input().split()))
	problems = []
	(all_a, all_b) = (0, 0)
	for i in range(n):
		if problem_type[i] == 0:
			all_a += 1
			problems.append((a, reqtime[i]))
		else:
			all_b += 1
			problems.append((b, reqtime[i]))
	reqtime.append(T + 1)
	reqtime = list(set(reqtime))
	reqtime.sort()
	problems.sort(key=lambda x: x[1])

	def max_getter(time_allowed, must_a, must_b, all_a, all_b):
		assert must_a <= all_a
		assert must_b <= all_b
		if a * must_a + b * must_b > time_allowed:
			return -1
		else:
			time_left = time_allowed - (a * must_a + b * must_b)
			(free_a, free_b) = (all_a - must_a, all_b - must_b)
			if time_left < free_a * a:
				return must_a + must_b + time_left // a
			else:
				time_left -= free_a * a
				return must_a + must_b + free_a + min(time_left // b, free_b)
	ans = 0
	idx = 0
	(must_a, must_b) = (0, 0)
	for v in reqtime:
		while idx < n and problems[idx][1] < v:
			if problems[idx][0] == a:
				must_a += 1
			else:
				must_b += 1
			idx += 1
		ans = max(ans, max_getter(v - 1, must_a, must_b, all_a, all_b))
	print(ans)
	return

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


res = []
for nt in range(int(input())):
	(n, t, a, b) = map(int, input().split())
	diff = list(map(int, input().split()))
	time = list(map(int, input().split()))
	count = diff.count(0)
	new = [(time[i], diff[i]) for i in range(n)]
	new.sort()
	ans = 0
	curr = 0
	k = 0
	c = 0
	while k < len(new) and curr <= t:
		d = new[k][0] - curr
		if d > 0:
			x = d // a
			if x <= count:
				if d % a == 0:
					ans = max(ans, c + x - 1)
				else:
					ans = max(ans, c + x)
			else:
				y = (d - count * a) // b
				if (d - count * a) % b == 0:
					ans = max(ans, c + y + count - 1)
				else:
					ans = max(ans, c + y + count)
		if new[k][1]:
			curr += b
		else:
			curr += a
			count -= 1
		c += 1
		k += 1
	if curr <= t:
		ans = max(ans, c)
	print(min(ans, n))


import sys
from operator import itemgetter

def count(a, b, num_a, num_b, cur_time):
	current_result = 0
	if num_a * a + num_b * b <= cur_time and cur_time >= 0:
		cur_time -= num_a * a + num_b * b
		current_result = num_a + num_b
		if num_a < total_a:
			if (total_a - num_a) * a <= cur_time:
				current_result += total_a - num_a
				cur_time -= (total_a - num_a) * a
			else:
				current_result += cur_time // a
				cur_time -= a * (cur_time // a)
		if num_b < total_b:
			if (total_b - num_b) * b <= cur_time:
				current_result += total_b - num_b
			else:
				current_result += cur_time // b
	return current_result

def solve(n, T, a, b, tasks, total_a, total_b):
	tasks = sorted(tasks)
	result = 0
	num_a = 0
	num_b = 0
	for i in range(len(tasks)):
		(time, t) = tasks[i]
		cur_time = time - 1
		current_result = count(a, b, num_a, num_b, cur_time)
		result = max(current_result, result)
		if t == 0:
			num_a += 1
		else:
			num_b += 1
		if i == len(tasks) - 1 or tasks[i + 1][1] != tasks[i][1]:
			result = max(result, count(a, b, num_a, num_b, cur_time))
	result = max(result, count(a, b, total_a, total_b, T))
	return result
q = int(input())
for i in range(q):
	(n, T, a, b) = map(int, input().split())
	types = list(map(int, input().split()))
	(total_a, total_b) = (0, 0)
	for t in types:
		if t == 0:
			total_a += 1
		else:
			total_b += 1
	t = list(map(int, input().split()))
	tasks = list(zip(t, types))
	print(solve(n, T, a, b, tasks, total_a, total_b))


from collections import Counter
from collections import defaultdict
import math

def inp():
	return map(int, input().split())
mod = int(1000000000.0) + 7
for _ in range(int(input())):
	(n, t, a, b) = inp()
	zo = list(inp())
	tim = list(inp())
	easy = zo.count(0)
	hard = n - easy
	lst = list(zip(tim, zo))
	lst.append((t + 1, 0))
	lst.sort()
	ans = 0
	count0 = 0
	count1 = 0
	i = 0
	while i < n + 1:
		costreq = count0 * a + count1 * b
		costsupply = lst[i][0] - 1 - costreq
		if costsupply >= 0:
			addeasy = min(costsupply // a, easy - count0)
			costsupply -= addeasy * a
			addhard = min(costsupply // b, hard - count1)
			ans = max(ans, count0 + count1 + addeasy + addhard)
		temp = i
		while temp < n + 1 and lst[i][0] == lst[temp][0]:
			if lst[temp][1]:
				count1 += 1
			else:
				count0 += 1
			temp += 1
		i = temp
	print(ans)


M = int(input())
for _ in range(M):
	(n, T, a, b) = map(int, input().split())
	ns = [a if x == '0' else b for x in input().split()]
	ts = [int(x) for x in input().split()]
	sort = sorted(list(zip(ns, ts)), key=lambda x: x[1])
	ns = [x[0] for x in sort]
	ts = [x[1] for x in sort] + [T + 1]
	best = 0
	tot = 0
	n_a = n_b = 0
	for x in ns:
		if x == a:
			n_a += 1
		else:
			n_b += 1

	def fill(x):
		if x <= 0:
			return 0
		if n_a * a >= x:
			return x // a
		else:
			x -= n_a * a
			if n_b * b >= x:
				return n_a + x // b
			return n_a + n_b
	for i in range(n):
		if tot < ts[i]:
			best = max(best, i + fill(ts[i] - 1 - tot))
		if ts[i] == ts[i + 1]:
			tot += ns[i]
			if ns[i] == a:
				n_a -= 1
			else:
				n_b -= 1
			continue
		tot += ns[i]
		if ns[i] == a:
			n_a -= 1
		else:
			n_b -= 1
		if tot <= ts[i]:
			best = max(best, i + 1 + fill(ts[i] - tot))
		if tot < ts[i + 1]:
			best = max(best, i + 1 + fill(ts[i + 1] - 1 - tot))
	assert n_a == n_b == 0
	if sum(ns) <= T:
		best = n
	if a > T:
		best = 0
	print(best)


for _ in range(int(input())):
	(n, t, a, b) = map(int, input().split())
	r = list(map(int, input().split()))
	s = list(map(int, input().split()))
	d = dict()
	hd = 0
	es = 0
	for i in range(n):
		if s[i] in d.keys():
			d[s[i]][r[i]] += 1
		else:
			d[s[i]] = [0, 0]
			d[s[i]][r[i]] += 1
		if r[i] == 0:
			es += 1
		else:
			hd += 1
	if 0 not in d.keys():
		d[0] = [0, 0]
	dd = list(d.keys())
	dd.sort()
	for i in range(1, len(dd)):
		d[dd[i]][0] += d[dd[i - 1]][0]
		d[dd[i]][1] += d[dd[i - 1]][1]
	ans = 0
	for i in range(1, len(dd)):
		easy = d[dd[i - 1]][0]
		hard = d[dd[i - 1]][1]
		time = dd[i] - 1
		if a * easy + b * hard <= time:
			a_plus = (time - a * easy - b * hard) // a
			a_plus = min(a_plus, es - easy)
			b_plus = (time - a * easy - b * hard - a_plus * a) // b
			b_plus = min(b_plus, hd - hard)
			ans = max(ans, easy + hard + a_plus + b_plus)
	if a * es + b * hd <= t:
		ans = es + hd
	print(ans)


for t in range(int(input())):
	(n, ti, a, b) = map(int, input().split())
	aa = list(map(int, input().split()))
	bb = list(map(int, input().split()))
	c = []
	count_eb = 0
	count_hb = 0
	count_ef = 0
	count_hf = 0
	for i in range(n):
		c.append([bb[i], aa[i]])
		if aa[i] == 1:
			count_hb += 1
		else:
			count_eb += 1
	c.sort()
	c.append([ti + 1, 0])
	count = 0
	store = 0
	for i in range(n + 1):
		diff = count_hf * b + count_ef * a
		count = 0
		if diff <= c[i][0] - 1 and diff <= ti:
			count = i
			vac_e = abs(diff - c[i][0] + 1)
			if count_eb * a > vac_e:
				rem = vac_e // a
			else:
				rem = count_eb
			count += rem
			vac_h = abs(vac_e - rem * a)
			if count_hb * b <= vac_h:
				count += count_hb
			else:
				count += vac_h // b
		store = max(store, count)
		if c[i][1] == 1:
			count_hb -= 1
			count_hf += 1
		else:
			count_eb -= 1
			count_ef += 1
	print(store)


t = int(input())
for _ in range(t):
	(n, T, a, b) = map(int, input().split())
	h1 = [int(x) for x in input().split()]
	h2 = [int(x) for x in input().split()]
	h1.append(0)
	h2.append(T + 1)
	h = sorted(zip(h2, h1))
	c0 = h1.count(0) - 1
	c1 = h1.count(1)
	ans = 0
	ptr = 0
	man = 0
	c = 0
	for i in range(0, len(h)):
		brk = h[i][0] - 1
		ex = max(0, brk - man)
		ex_task = 0
		t1 = min(c0, ex // a)
		ex -= t1 * a
		t2 = min(c1, ex // b)
		ex -= t2 * b
		ex_task += t1 + t2
		if brk >= man:
			ans = max(ans, ex_task + i)
		if h[i][1] == 1:
			man += b
			c1 -= 1
		else:
			man += a
			c0 -= 1
	print(ans)


ssss = int(input())
for _ in range(ssss):
	(n, t, a, b) = map(int, input().split())
	o = list(map(int, input().split()))
	s = list(map(int, input().split()))
	la = sum([1 for i in o if i == 0])
	lb = sum([1 for i in o if i == 1])
	ps = [(o[i], s[i]) for i in range(n)]
	d = {}
	cd = {}
	dla = {}
	dlb = {}
	sm = smt = 0
	ans = 0
	ag = {}
	for p in ps:
		if p[1] not in ag:
			ag[p[1]] = []
		ag[p[1]].append(b if p[0] else a)
	ks = sorted(list(set([p[1] for p in ps])))
	for k in ks:
		d[k - 1] = sm
		cd[k - 1] = smt
		dla[k - 1] = la
		dlb[k - 1] = lb
		sm += sum(ag[k])
		smt += len(ag[k])
		tmp = len([i for i in ag[k] if i == a])
		la -= tmp
		lb -= len(ag[k]) - tmp
	ts = sorted(list(d.items()), key=lambda x: x[0])
	ts.append((t, sm))
	cd[t] = n
	ans = 0
	for tss in ts:
		ft = tss[0] - tss[1]
		if ft >= 0:
			if tss[0] == t:
				ans = max(ans, n)
				break
			cans = cd[tss[0]]
			csa = min(ft // a, dla[tss[0]])
			cans += csa
			ft -= csa * a
			csb = min(ft // b, dlb[tss[0]])
			cans += csb
			ft -= csb * b
			ans = max(ans, cans)
	print(ans)


m = int(input())
for ii in range(m):
	(n, T, a, b) = list(map(int, input().split()))
	score = [a, b]
	d = list(map(int, input().split()))
	t = list(map(int, input().split()))
	easy = 0
	for d1 in d:
		if d1 == 0:
			easy += 1
	diff = zip(t, d)
	diff = sorted(diff)
	cnt = 0
	cur = 0
	ans = 0
	for i in range(n):
		(t, d) = diff[i]
		if cur < t and cur <= T:
			ans = max(cnt, ans)
			tmp = (t - 1 - cur) // a
			tmp = min(tmp, easy)
			ans = max(ans, cnt + tmp)
		cnt += 1
		cur += score[d]
		if d == 0:
			easy -= 1
	if cur <= T:
		ans = max(cnt, ans)
	print(ans)


from sys import stderr
m = int(input())
for _ in range(m):
	(n, T, a, b) = list(map(int, input().split()))
	c = [a, b]
	ty = list(map(int, input().split()))
	ca = n - sum(ty)
	cb = n - ca
	time = list(map(int, input().split()))
	items = list(zip(time, ty))
	items.sort()
	ans = 0
	t = 0
	count = [0, 0]
	print(ca, cb, file=stderr)
	for i in range(n):
		if t > T:
			break
		if t < items[i][0]:
			temp = max(0, min(ca - count[0], (items[i][0] - 1 - t) // a))
			ans = max(ans, count[0] + count[1] + temp + max(0, min(cb - count[1], (items[i][0] - 1 - t - temp * a) // b)))
		count[items[i][1]] += 1
		t += c[items[i][1]]
	if t <= T:
		ans = n
	print(file=stderr)
	print(ans)


from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 10 ** 9 + 7

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

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

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

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

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n').split(' ')]

def li3():
	return [int(i) for i in input().rstrip('\n')]

def compare(a, b):
	if a[0] == b[0]:
		if a[1] < b[1]:
			return -1
		return 1
	return -1 if a[0] < b[0] else 1
for _ in range(val()):
	(n, T, A, B) = li()
	level = li()
	time = li()
	ques = [[i, j] for (i, j) in zip(level, time)]
	(tota, totb) = (0, 0)
	for i in ques:
		if i[0]:
			totb += 1
		else:
			tota += 1
	ques.sort(key=lambda x: x[1])
	mandatory = {}
	prev = [0, 0]
	for i in range(n):
		prev[ques[i][0]] += 1
		mandatory[ques[i][1]] = tuple(prev)
	mandatory[T] = tuple(prev)
	if 0 not in mandatory:
		mandatory[0] = tuple([0, 0])
	timemandatory = sorted(list(mandatory))
	for i in range(1, len(timemandatory)):
		if timemandatory[i] - 1 not in mandatory:
			mandatory[timemandatory[i] - 1] = mandatory[timemandatory[i - 1]]
	timemandatory = sorted(list(mandatory))
	curr = [0, 0]
	ans = 0
	for i in timemandatory:
		rema = tota - mandatory[i][0]
		remb = totb - mandatory[i][1]
		remtime = i - (mandatory[i][0] * A + mandatory[i][1] * B)
		curr = sum(mandatory[i])
		if remtime >= 0:
			more = min(remtime // A, rema)
			remtime -= A * min(remtime // A, rema)
			more += min(remtime // B, remb)
			ans = max(ans, more + curr)
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for testcases in range(t):
	(n, T, a, b) = list(map(int, input().split()))
	A = list(map(int, input().split()))
	L = list(map(int, input().split()))
	LCAN = [T]
	EASY = []
	HARD = []
	for i in range(n):
		if A[i] == 0:
			EASY.append(L[i])
		else:
			HARD.append(L[i])
		if L[i] > 1:
			LCAN.append(L[i] - 1)
	LCAN = sorted(set(LCAN))
	EASY.sort()
	HARD.sort()
	eind = 0
	hind = 0
	LENE = len(EASY)
	LENH = len(HARD)
	needtime = 0
	ANS = 0
	for time in LCAN:
		while eind < LENE and EASY[eind] <= time:
			needtime += a
			eind += 1
		while hind < LENH and HARD[hind] <= time:
			needtime += b
			hind += 1
		if time < needtime:
			continue
		else:
			rest = time - needtime
			score = eind + hind
			if (LENE - eind) * a >= rest:
				score += rest // a
			else:
				score = LENE + hind
				rest -= (LENE - eind) * a
				score += min(LENH - hind, rest // b)
			ANS = max(ANS, score)
	print(ANS)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def solve():
	(n, T, a, b) = map(int, input().split())
	c = list(map(int, input().split()))
	t = list(map(int, input().split()))
	hard = sum(c)
	easy = n - hard
	from collections import defaultdict
	d = defaultdict(lambda : [0, 0])
	for (ti, w) in zip(t, c):
		d[ti][w] += 1
	d[T + 1]
	t_set = sorted(set(t)) + [T + 1]
	now_easy = 0
	now_hard = 0
	ans = 0
	for ti in t_set:
		cnt = now_easy + now_hard
		need = now_easy * a + now_hard * b
		remain_easy = easy - now_easy
		remain_hard = hard - now_hard
		now_easy += d[ti][0]
		now_hard += d[ti][1]
		if need > ti - 1:
			continue
		use_easy = min(remain_easy, (ti - 1 - need) // a)
		cnt += use_easy
		need += a * use_easy
		use_hard = min(remain_hard, (ti - 1 - need) // b)
		cnt += use_hard
		ans = max(ans, cnt)
	print(ans)
t = int(input())
for i in range(t):
	solve()


from collections import deque
t = int(input())
for test in range(t):
	(n, T, a, b) = list(map(int, input().split()))
	hardness = list(map(int, input().split()))
	time = list(map(int, input().split()))
	easy = {}
	hard = {}
	req_time = 0
	for i in time:
		easy[i] = 0
		hard[i] = 0
	for i in range(n):
		if hardness[i] == 0:
			easy[time[i]] += 1
			req_time += a
		else:
			hard[time[i]] += 1
			req_time += b
	time.sort(reverse=True)
	ans = n
	if req_time <= T:
		print(ans)
	else:
		ans = 0
		ques = n
		seen = set()
		easy_count = 0
		hard_count = 0
		for i in time:
			if i not in seen:
				seen.add(i)
				easy_count += easy[i]
				hard_count += hard[i]
				req_time -= a * easy[i]
				req_time -= b * hard[i]
				ques -= easy[i]
				ques -= hard[i]
				if req_time <= i - 1:
					num_easy = min((i - 1 - req_time) // a, easy_count)
					num_hard = min((i - 1 - req_time - num_easy * a) // b, hard_count)
					ans = max(ans, ques + num_easy + num_hard)
		print(ans)


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')
m = int(input())
for i in range(m):
	time = [0, 0]
	(n, T, time[0], time[1]) = map(int, input().split())
	d = [0, 0]
	c = list(map(int, input().split()))
	t = list(map(int, input().split()))
	l = []
	for j in range(n):
		l.append([t[j], c[j]])
		d[c[j]] += 1
	l.sort()
	ans = 0
	l.append([T + 1, 0])
	pre = 0
	for j in range(n + 1):
		if j != n:
			d[l[j][1]] -= 1
		if pre < l[j][0]:
			cur = j
			left = l[j][0] - 1 - pre
			sml = left // time[0]
			if sml >= d[0]:
				cur += d[0]
				left -= time[0] * d[0]
				big = left // time[1]
				cur += min(d[1], big)
			else:
				cur += sml
			ans = max(ans, cur)
		pre += time[l[j][1]]
	print(ans)


T = int(input())
for _ in range(T):
	(n, t, a, b) = map(int, input().split())
	a1 = list(map(int, input().split()))
	t1 = list(map(int, input().split()))
	arr = []
	c0 = 0
	c1 = 0
	for i in a1:
		if i:
			c1 += 1
		else:
			c0 += 1
	for i in range(n):
		arr.append([t1[i], a1[i]])
	arr.sort()
	ans = 0
	s = [0, 0]
	for i in range(n):
		z = s[0] * a + s[1] * b
		if z >= arr[i][0]:
			x = 0
		else:
			p = min(c0, (arr[i][0] - z - 1) // a)
			q = min(c1, (arr[i][0] - z - p * a - 1) // b)
			x = sum(s) + p + q
		ans = max(ans, x)
		if arr[i][1] == 0:
			s[0] += 1
			c0 -= 1
		else:
			s[1] += 1
			c1 -= 1
	z = s[0] * a + s[1] * b
	if z > t:
		x = 0
	else:
		p = min(c0, (t - z) // a)
		q = min(c1, (t - z - p * a) // b)
		x = sum(s) + p + q
	ans = max(ans, x)
	print(ans)


import sys
input = sys.stdin.readline

def solve(time, measy, mhard, teasy, thard):
	if measy * a + mhard * b > time:
		return 0
	ret = measy + mhard
	time -= measy * a + mhard * b
	x = min(time // a, teasy - measy)
	ret += x
	time -= a * x
	y = min(time // b, thard - mhard)
	ret += y
	return ret
t = int(input())
for _ in range(t):
	(n, T, a, b) = map(int, input().split())
	d = list(map(int, input().split()))
	m = list(map(int, input().split()))
	A = []
	for i in range(n):
		A.append(m[i] * 10 + d[i])
	A.sort()
	teasy = d.count(0)
	thard = d.count(1)
	(measy, mhard) = (0, 0)
	ans = 0
	for i in range(n):
		(time, dd) = divmod(A[i], 10)
		time -= 1
		cur = solve(time, measy, mhard, teasy, thard)
		ans = max(ans, cur)
		if dd:
			mhard += 1
		else:
			measy += 1
	cur = solve(T, measy, mhard, teasy, thard)
	ans = max(ans, cur)
	print(ans)


from operator import itemgetter
import sys
input = sys.stdin.readline
m = int(input())
for _ in range(m):
	(n, time, a, b) = map(int, input().split())
	flag = [list(map(int, input().split())) for i in range(2)]
	t = zip(*flag)
	t = sorted(t)
	t = sorted(t, key=itemgetter(1))
	memo = {}
	memo[0] = 0
	memo[1] = 0
	for i in range(n):
		memo[t[i][0]] += 1
	t.append((0, time + 1))
	ans = 0
	cnt = 0
	num = 0
	for i in range(n + 1):
		(flg, tt) = t[i]
		tmp_ans = cnt
		nokori = tt - 1 - num
		if nokori < 0:
			pass
		else:
			tmp_cnt = min(memo[0], nokori // a)
			tmp_ans += tmp_cnt
			tmp_ans += min(memo[1], (nokori - tmp_cnt * a) // b)
			ans = max(ans, tmp_ans)
		cnt += 1
		if flg == 0:
			num += a
		else:
			num += b
		memo[flg] -= 1
	print(ans)


m = int(input())
for i in range(m):
	(n, T, a, b) = list(map(int, input().split()))
	is_hard = list(map(int, input().split()))
	total_hard = sum(is_hard)
	total_easy = n - total_hard
	time_mandatory = list(map(int, input().split()))
	mandatory_times = sorted([(time_mandatory[i], i) for i in range(len(time_mandatory))])
	mandatory_times.append((T, -1))
	maximal_points = 0
	min_easy = 0
	min_hard = 0
	for (i, (time, problem_no)) in enumerate(mandatory_times):
		bad = False
		if i != len(mandatory_times) - 1 and mandatory_times[i + 1][0] == time:
			bad = True
		remaining_easy = total_easy - min_easy
		remaining_hard = total_hard - min_hard
		remaining_time = time - 1 - min_easy * a - min_hard * b
		if remaining_time >= 0:
			if remaining_time >= a * remaining_easy:
				maximal_points = max(maximal_points, min_easy + min_hard + remaining_easy + min((remaining_time - a * remaining_easy) // b, remaining_hard))
			else:
				maximal_points = max(maximal_points, min_easy + min_hard + remaining_time // a)
		if problem_no == -1:
			min_easy = min_easy
		elif is_hard[problem_no] == 1:
			min_hard += 1
		else:
			min_easy += 1
		if bad:
			continue
		remaining_easy = total_easy - min_easy
		remaining_hard = total_hard - min_hard
		remaining_time = time - min_easy * a - min_hard * b
		if remaining_time >= 0:
			if remaining_time >= a * remaining_easy:
				maximal_points = max(maximal_points, min_easy + min_hard + remaining_easy + min((remaining_time - a * remaining_easy) // b, remaining_hard))
			else:
				maximal_points = max(maximal_points, min_easy + min_hard + remaining_time // a)
	print(maximal_points)


case = int(input())
number = []
for i in range(case):
	c = input()
	c = c.split()
	n = int(c[0])
	T = int(c[1])
	a = int(c[2])
	b = int(c[3])
	problem = input()
	problem = list(map(int, problem.split()))
	time = input()
	time = list(map(int, time.split()))
	time_order = sorted(range(len(time)), key=lambda k: time[k])
	time_step = []
	easy_num = []
	hard_num = []
	easy_count = 0
	hard_count = 0
	time_step.append(time[time_order[0]])
	if problem[time_order[0]] == 0:
		easy_count += 1
	else:
		hard_count += 1
	for j in range(1, n):
		if time[time_order[j]] != time[time_order[j - 1]]:
			easy_num.append(easy_count)
			hard_num.append(hard_count)
			easy_count = 0
			hard_count = 0
			time_step.append(time[time_order[j]])
		if problem[time_order[j]] == 0:
			easy_count += 1
		else:
			hard_count += 1
	easy_num.append(easy_count)
	hard_num.append(hard_count)
	easy_sum = sum(easy_num)
	total_easy = easy_sum
	hard_sum = sum(hard_num)
	total_hard = hard_sum
	if easy_sum * a + hard_sum * b <= T:
		total = easy_sum + hard_sum
	else:
		total = 0
	if total == 0:
		temp = 0
		for j in range(len(time_step) - 1, -1, -1):
			T = time_step[j] - 1
			easy_sum -= easy_num[j]
			hard_sum -= hard_num[j]
			solve_time = easy_sum * a + hard_sum * b
			easy_left = total_easy - easy_sum
			if solve_time <= T:
				temp = easy_sum + hard_sum
				rest = int((T - solve_time) / a)
				if rest <= easy_left:
					temp += rest
				else:
					temp += int((T - solve_time - easy_left * a) / b) + easy_left
				total = max(total, temp)
	number.append(total)
for i in range(case):
	print(number[i])


import sys

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

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	(n, T, a, b) = mints()
	h = list(mints())
	c = [0, 0]
	for i in h:
		c[i] += 1
	i = 0
	t = [None] * n
	for j in mints():
		t[i] = (j, i)
		i += 1
	t.sort()
	tt = 0
	tmust = 0
	cmust = 0
	r = 0
	for ii in range(len(t)):
		(tn, i) = t[ii]
		if tt < tn - 1:
			tt = tn - 1
			left = tt - tmust
			if left >= 0:
				ac = min(left // a, c[0])
				bc = min((left - ac * a) // b, c[1])
				r = max(r, cmust + ac + bc)
		if h[i]:
			tmust += b
			c[1] -= 1
		else:
			tmust += a
			c[0] -= 1
		cmust += 1
	if tt < T:
		tt = T
		left = tt - tmust
		if left >= 0:
			ac = min(left // a, c[0])
			bc = min((left - ac * a) // b, c[1])
			r = max(r, cmust + ac + bc)
	return r
for i in range(mint()):
	print(solve())


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush

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())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

def main():
	for _ in range(N()):
		(n, t, a, b) = RL()
		eh = RLL()
		rq = RLL()
		q = list(zip(eh, rq))
		q.sort(key=lambda a: a[1])
		q.append([2, t + 1])
		S = eh.count(0)
		H = n - S
		res = 0
		ss = hh = 0
		for i in range(n + 1):
			(dg, tm) = q[i]
			pret = ss * a + hh * b
			if pret <= tm - 1:
				(ds, dt) = (S - ss, H - hh)
				now = ss + hh
				dif = tm - 1 - pret
				if dif > 0:
					now += min(ds, dif // a)
					dif -= min(ds, dif // a) * a
					if dif > 0:
						now += min(dt, dif // b)
				res = max(res, now)
			if dg == 0:
				ss += 1
			else:
				hh += 1
		print(res)
main()


from operator import itemgetter
t = int(input())

def non_mandatory(time, n_easy, n_hard, a, b):
	s_easy = min(n_easy, time // a)
	time -= a * s_easy
	s_hard = min(n_hard, time // b)
	return s_easy + s_hard

def solve(n, T, a, b, eh, t):
	teh = [(t[i], eh[i]) for i in range(n)]
	teh.sort(key=itemgetter(0))
	points = []
	m_time = 0
	e_remain = len([0 for i in eh if i == 0])
	h_remain = n - e_remain
	point = non_mandatory(teh[0][0] - 1, e_remain, h_remain, a, b)
	points.append(point)
	for i in range(1, n):
		if not teh[i - 1][1]:
			m_time += a
			e_remain -= 1
		else:
			m_time += b
			h_remain -= 1
		if teh[i][0] - 1 - m_time >= 0:
			point = i + non_mandatory(teh[i][0] - 1 - m_time, e_remain, h_remain, a, b)
		else:
			point = 0
		points.append(point)
	if not teh[n - 1][1]:
		m_time += a
		e_remain -= 1
	else:
		m_time += b
		h_remain -= 1
	if T - m_time >= 0:
		point = n
	else:
		point = 0
	points.append(point)
	print(max(points))
for i in range(t):
	(n, T, a, b) = map(int, input().split())
	eh = list(map(int, input().split()))
	t = list(map(int, input().split()))
	solve(n, T, a, b, eh, t)


for _ in range(int(input())):
	(n, t, a, b) = map(int, input().split())
	pt = [int(o) for o in input().split()]
	times = [int(o) for o in input().split()]
	d = dict()
	for i in range(n):
		try:
			d[times[i]].append(pt[i])
		except:
			d[times[i]] = [pt[i]]
	times = sorted(list(set(times)))
	n1 = len(times)
	c0 = pt.count(0)
	c1 = pt.count(1)
	c11 = c1
	c00 = c0
	ans = [0]
	ct = 0
	lol = 0
	times.append(float('inf'))
	for i in range(n1):
		c0t = c0
		c1t = c1
		ctt = ct
		lolt = 0
		trr = times[i] - ctt - 1
		if trr > 0:
			x = trr // a
			if x <= c0t:
				c0t -= x
				trr = 0
				ctt += x * a
				lolt += x
			else:
				ctt += c0t * a
				lolt += c0t
				trr -= c0t * a
				c0t = 0
			x = trr // b
			if x <= c1t:
				c1t -= x
				trr = 0
				ctt += x * b
				lolt += x
			else:
				ctt += c1t * b
				lolt += c1t
				trr -= c1t * b
				c1t = 0
		if ctt <= t and ctt < times[i]:
			ans.append(lol + lolt)
		for j in d[times[i]]:
			if j == 1:
				ct += b
				c1 -= 1
				lol += 1
			else:
				ct += a
				c0 -= 1
				lol += 1
	if a * c00 + b * c11 <= t:
		ans.append(n)
	print(max(ans))


def solve():
	(nproblems, tottime, a, b) = map(int, input().split())
	diffls = list(map(int, input().split()))
	mandls = list(map(int, input().split()))
	ls = []
	for i in range(nproblems):
		ls.append((mandls[i], diffls[i]))
	ls.sort()
	nez = diffls.count(0)
	mandtime = 0
	ptr = 0
	ezmand = 0
	best = 0
	while ptr < nproblems:
		mandtime += b if ls[ptr][1] else a
		ezmand += 0 if ls[ptr][1] else 1
		while ptr + 1 < nproblems and ls[ptr + 1][0] == ls[ptr][0]:
			ptr += 1
			mandtime += b if ls[ptr][1] else a
			ezmand += 0 if ls[ptr][1] else 1
		if ptr + 1 < nproblems:
			timeleft = ls[ptr + 1][0] - mandtime - 1
		else:
			timeleft = tottime - mandtime
		if timeleft >= 0 and mandtime <= tottime:
			bonusa = min(timeleft // a, nez - ezmand)
			tafta = mandtime + bonusa * a
			if ptr + 1 < nproblems:
				timeleftb = ls[ptr + 1][0] - tafta - 1
			else:
				timeleftb = tottime - tafta
			bonusb = max(0, min(timeleftb // b, nproblems - (ptr + 1 + bonusa)))
			best = max(best, ptr + 1 + bonusa + bonusb)
		ptr += 1
	timeleft = ls[0][0] - 1
	bonusa = min(timeleft // a, nez)
	tafta = bonusa * a
	timeleftb = ls[0][0] - tafta - 1
	bonusb = max(0, min(timeleftb // b, nproblems - nez))
	best = max(best, bonusa + bonusb)
	print(best)
for tcase in range(int(input())):
	solve()


import os
from io import BytesIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	(n, T, a, b) = map(int, input().split())
	hard = [bool(i) for i in map(int, input().split())]
	time = [(int(i), ind) for (ind, i) in enumerate(input().split())]
	time.sort()
	i = 0
	cnteasy = hard.count(False)
	cnthard = n - cnteasy
	if (time[0][0] - 1) // a <= cnteasy:
		ans = (time[0][0] - 1) // a
	else:
		ans = cnteasy + min((time[0][0] - 1 - cnteasy * a) // b, cnthard)
	ans = max(ans, 0)
	eas = 0
	har = 0
	while i < n:
		if hard[time[i][1]]:
			har += 1
		else:
			eas += 1
		while i < n - 1 and time[i + 1][0] == time[i][0]:
			i += 1
			if hard[time[i][1]]:
				har += 1
			else:
				eas += 1
		if i < n - 1:
			free_time = min(time[i + 1][0] - 1, T)
		else:
			free_time = T
		if free_time < har * b + eas * a:
			i += 1
			continue
		else:
			curans = har + eas
			free_time -= har * b + eas * a
			if free_time // a <= cnteasy - eas:
				curans += free_time // a
			else:
				free_time -= (cnteasy - eas) * a
				curans += cnteasy - eas + min(free_time // b, cnthard - har)
			ans = max(curans, ans)
		i += 1
	print(ans)


import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	(n, t, a, b) = [int(i) for i in input().split()]
	d = [int(i) for i in input().split()]
	ti = [int(i) for i in input().split()]
	arr = []
	for i in range(n):
		arr.append([ti[i], d[i]])
	arr.sort()
	t1 = []
	d1 = []
	for i in arr:
		t1.append(i[0])
		d1.append(i[1])
	ans = 0
	easy = 0
	if d1[0] == 0:
		now = a
		easy += 1
	else:
		now = b
	curr = 1
	teasy = d1.count(0)
	final = max(min((t1[0] - 1) // a, teasy), 0)
	while now <= t and curr < n:
		if t1[curr] > now:
			ans = curr
			rem = teasy - easy
			diff = t1[curr] - now
			can = (diff - 1) // a
			final = max(final, ans + min(can, rem))
		if d1[curr] == 0:
			now += a
			easy += 1
		else:
			now += b
		curr += 1
	if now <= t:
		ans = curr
		final = curr
	print(final)


import os, sys
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		(n, T, a, b) = map(int, input().split())
		t = [[b1, a1] for (a1, b1) in zip(map(int, input().split()), map(int, input().split()))]
		t.sort(key=lambda xx: xx[0])
		ans = 0
		arr = [[0, 0, 0]]
		for i in t:
			if arr[-1][2] < i[0] - 1:
				arr.append(arr[-1][:])
				arr[-1][2] = i[0] - 1
			if arr[-1][2] < i[0]:
				arr.append(arr[-1][:])
				arr[-1][2] = i[0]
			if i[1]:
				arr[-1][1] += 1
			else:
				arr[-1][0] += 1
		arr.append([arr[-1][0], arr[-1][1], T])
		(t1, t2) = (arr[-1][0], arr[-1][1])
		for i in arr:
			y = i[0] * a + i[1] * b
			if y <= i[2]:
				ex1 = min(t1 - i[0], (i[2] - y) // a)
				ex2 = min(t2 - i[1], (i[2] - y - ex1 * a) // b)
				ans = max(ans, i[1] + i[0] + ex1 + ex2)
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


from collections import defaultdict as dd
import math
import sys

def nn():
	return int(input())

def li():
	return list(input())

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

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

def solve(N, T, easy_cost, hard_cost, dat):
	dat.sort()
	num_easy = sum((1 for x in dat if not x[1]))
	num_hard = len(dat) - num_easy
	best = 0
	cost_first_k = 0
	easies_done = 0
	budget = dat[0][0] - 1
	first_0 = budget // easy_cost
	first_0 = min(first_0, num_easy)
	best = max(best, first_0)
	for k in range(N):
		cost_one = hard_cost if dat[k][1] else easy_cost
		cost_first_k += cost_one
		easy_remaining = num_easy - easies_done
		hard_remaining = num_hard - (k - easies_done)
		if dat[k][1]:
			hard_remaining -= 1
		else:
			easies_done += 1
			easy_remaining -= 1
		if cost_first_k > T:
			break
		budget = T - cost_first_k
		if k < N - 1:
			budget = min(budget, dat[k + 1][0] - 1 - cost_first_k)
		if budget < 0:
			continue
		if easy_cost * easy_remaining >= budget:
			extra_easy = budget // easy_cost
			extra_hard = 0
		else:
			extra_easy = easy_remaining
			budget -= easy_cost * easy_remaining
			if hard_cost * hard_remaining >= budget:
				extra_hard = budget // hard_cost
			else:
				extra_hard = hard_remaining
		curr = k + 1 + extra_easy + extra_hard
		best = max(best, curr)
	return best

def helper():
	(N, T, easy_cost, hard_cost) = mi()
	dat_types = lm()
	dat_cutoffs = lm()
	dat = [(c, t == 1) for (c, t) in zip(dat_cutoffs, dat_types)]
	print(solve(N, T, easy_cost, hard_cost, dat))
T = nn()
for _ in range(T):
	helper()


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	(n, t, a, b) = map(int, input().split())
	qi = list(map(int, input().split()))
	ti = list(map(int, input().split()))
	e = []
	ea = qi.count(0)
	ha = qi.count(1)
	for i in range(n):
		e.append([ti[i], qi[i]])
	e.sort()
	ans = 0
	te = 0
	s = [0, 0]
	for i in range(n):
		to = s[0] * a + s[1] * b
		if to >= e[i][0]:
			x = 0
		else:
			p = min(ea, (e[i][0] - to - 1) // a)
			q = min(ha, (e[i][0] - to - p * a - 1) // b)
			x = sum(s) + p + q
		ans = max(ans, x)
		if e[i][1] == 0:
			s[0] += 1
			ea -= 1
		else:
			s[1] += 1
			ha -= 1
	to = s[0] * a + s[1] * b
	if to > t:
		x = 0
	else:
		p = min(ea, (t - to) // a)
		q = min(ha, (t - to - p * a) // b)
		x = sum(s) + p + q
	ans = max(ans, x)
	print(ans)


def Input():
	tem = input().split()
	ans = []
	for it in tem:
		ans.append(int(it))
	return ans
TT = Input()[0]
for tt in range(TT):
	(n, T, a, b) = Input()
	pro = Input()
	t = Input()
	ma = {}
	last = [0, 0]
	for i in range(n):
		if t[i] not in ma.keys():
			ma[t[i]] = [0, 0]
			ma[t[i]][pro[i]] += 1
			last[pro[i]] += 1
		else:
			ma[t[i]][pro[i]] += 1
			last[pro[i]] += 1
	ma[T + 1] = [last[0], last[1]]
	ma_list = list(ma.keys())
	ma_list.sort()
	m = len(ma_list)
	must = [0, 0]
	ans = 0
	for i in range(m):
		remain = ma_list[i] - 1
		must_cost = must[0] * a + must[1] * b
		if remain < must_cost:
			for j in range(2):
				must[j] += ma[ma_list[i]][j]
				last[j] -= ma[ma_list[i]][j]
		else:
			tem_must = sum(must)
			remain -= must_cost
			new_a = min(remain // a, last[0])
			remain -= new_a * a
			new_b = min(remain // b, last[1])
			ans = max(ans, tem_must + new_a + new_b)
			for j in range(2):
				must[j] += ma[ma_list[i]][j]
				last[j] -= ma[ma_list[i]][j]
	print(ans)


for _ in range(int(input())):
	(n, t, a, b) = map(int, input().split())
	qi = list(map(int, input().split()))
	ti = list(map(int, input().split()))
	e = []
	ea = qi.count(0)
	ha = qi.count(1)
	for i in range(n):
		e.append([ti[i], qi[i]])
	e.sort()
	ans = 0
	te = 0
	s = [0, 0]
	for i in range(n):
		to = s[0] * a + s[1] * b
		if to >= e[i][0]:
			x = 0
		else:
			p = min(ea, (e[i][0] - to - 1) // a)
			q = min(ha, (e[i][0] - to - p * a - 1) // b)
			x = sum(s) + p + q
		ans = max(ans, x)
		if e[i][1] == 0:
			s[0] += 1
			ea -= 1
		else:
			s[1] += 1
			ha -= 1
	to = s[0] * a + s[1] * b
	if to > t:
		x = 0
	else:
		p = min(ea, (t - to) // a)
		q = min(ha, (t - to - p * a) // b)
		x = sum(s) + p + q
	ans = max(ans, x)
	print(ans)


M = int(input())

def foo(A, B, T, free_easy, free_hard, req_easy, req_hard):
	ans = 0
	T -= req_easy * A + req_hard * B
	if T < 0:
		return 0
	ans += req_easy + req_hard
	can_easy = min(free_easy, T // A)
	ans += can_easy
	T -= A * can_easy
	can_hard = min(free_hard, T // B)
	ans += can_hard
	T -= A * can_hard
	return ans

def solve():
	[N, T, A, B] = list(map(int, input().split()))
	Hard = list(map(int, input().split()))
	Req = list(map(int, input().split()))
	problems = zip(Req, Hard)
	time_to_req = {}
	for (t, h) in problems:
		if t not in time_to_req:
			time_to_req[t] = [0, 0]
		time_to_req[t][h] += 1
	free_hard = sum(Hard)
	free_easy = N - free_hard
	req_hard = 0
	req_easy = 0
	problems = [(t, time_to_req[t]) for t in time_to_req]
	problems = sorted(problems, key=lambda x: x[0])
	ans = 0
	for (t, eh) in problems:
		ans = max(ans, foo(A, B, t - 1, free_easy, free_hard, req_easy, req_hard))
		[easy, hard] = eh
		free_hard -= hard
		req_hard += hard
		free_easy -= easy
		req_easy += easy
	ans = max(ans, foo(A, B, T, 0, 0, req_easy, req_hard))
	return ans
for _ in range(M):
	print(solve())


m = int(input())
for case_num in range(m):
	(n, T, a, b) = map(int, input().split(' '))
	d = list(map(int, input().split(' ')))
	t = list(map(int, input().split(' ')))
	critical = set()
	for ti in t:
		critical.add(ti)
		if ti >= 1:
			critical.add(ti - 1)
	critical.add(T)
	critical = list(critical)
	critical.sort()
	k = len(critical)
	lut = dict()
	for i in range(k):
		lut[critical[i]] = i
	easy = [0 for i in range(k)]
	hard = [0 for i in range(k)]
	for i in range(n):
		idx = lut[t[i]]
		if d[i] == 0:
			easy[idx] += 1
		else:
			hard[idx] += 1
	mandatory_easy = 0
	mandatory_hard = 0
	total_hard = sum(d)
	total_easy = n - total_hard
	ans = 0
	for i in range(k):
		mandatory_easy += easy[i]
		mandatory_hard += hard[i]
		time = critical[i] - mandatory_easy * a - mandatory_hard * b
		if time < 0:
			continue
		rest_easy = total_easy - mandatory_easy
		extra_easy = min(time // a, rest_easy)
		time -= extra_easy * a
		rest_hard = total_hard - mandatory_hard
		extra_hard = min(time // b, rest_hard)
		score = mandatory_easy + mandatory_hard + extra_easy + extra_hard
		ans = max(ans, score)
	print(ans)


import sys
t = int(input())
ans = [0] * t
for pi in range(t):
	(n, T, a, b) = map(int, sys.stdin.readline().split())
	a1 = list(map(int, sys.stdin.readline().split()))
	a2 = list(map(int, sys.stdin.readline().split()))
	easy_count = a1.count(0)
	hard_count = n - easy_count
	tasks = sorted(((t, x) for (x, t) in zip(a1, a2)))
	solved = 0
	(req_easy, req_hard) = (0, 0)
	for (i, (t, is_hard)) in enumerate(tasks, start=1):
		rem = t - 1 - req_easy * a - req_hard * b
		if rem >= 0:
			c = min(easy_count - req_easy, rem // a)
			c += min(hard_count - req_hard, (rem - c * a) // b)
			solved = max(solved, c + req_easy + req_hard)
		if is_hard == 1:
			req_hard += 1
		else:
			req_easy += 1
	if easy_count * a + hard_count * b <= T:
		solved = n
	ans[pi] = solved
print(*ans, sep='\n')


def main():

	def calcTotalTime(easyCnts, hardCnts):
		return a * easyCnts + b * hardCnts
	m = int(input())
	allans = []
	for _ in range(m):
		(n, T, a, b) = readIntArr()
		ease = readIntArr()
		t = readIntArr()
		et = []
		easyCnts = 0
		hardCnts = 0
		for i in range(n):
			et.append([ease[i], t[i]])
			if ease[i] == 0:
				easyCnts += 1
			else:
				hardCnts += 1
		et.append([-1, 0])
		n += 1
		et.sort(key=lambda x: x[1])
		easyCumu = [0 for _ in range(n)]
		hardCumu = [0 for _ in range(n)]
		for i in range(n):
			if et[i][0] == 0:
				easyCumu[i] += 1
			elif et[i][0] == 1:
				hardCumu[i] += 1
			if i > 0:
				easyCumu[i] += easyCumu[i - 1]
				hardCumu[i] += hardCumu[i - 1]
		maxScore = 0
		for i in range(n):
			e = easyCumu[i]
			h = hardCumu[i]
			if calcTotalTime(e, h) > T or (i + 1 < n and calcTotalTime(e, h) >= et[i + 1][1]):
				continue
			binn = easyCnts
			while binn > 0:
				while e + binn <= easyCnts and calcTotalTime(e + binn, h) <= T and (i == n - 1 or calcTotalTime(e + binn, h) < et[i + 1][1]):
					e += binn
				binn //= 2
			binn = hardCnts
			while binn > 0:
				while h + binn <= hardCnts and calcTotalTime(e, h + binn) <= T and (i == n - 1 or calcTotalTime(e, h + binn) < et[i + 1][1]):
					h += binn
				binn //= 2
			maxScore = max(maxScore, e + h)
		allans.append(maxScore)
	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()]

def makeArr(defaultVal, dimensionArr):
	dv = defaultVal
	da = dimensionArr
	if len(da) == 1:
		return [dv for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(x, y):
	print('? {} {}'.format(x, y))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
	(N, T, a, b) = map(int, input().split())
	Es = list(map(int, input().split()))
	Ts = list(map(int, input().split()))
	Query.append((N, T, a, b, Es, Ts))
for (N, T, a, b, Es, Ts) in Query:
	P = []
	remain_a = 0
	remain_b = 0
	for (e, t) in zip(Es, Ts):
		if e == 0:
			P.append((t, a))
			remain_a += 1
		else:
			P.append((t, b))
			remain_b += 1
	P.sort()
	t = 0
	ans = 0
	for (i, (deadline, needtime)) in enumerate(P):
		if t < deadline:
			remain_time = deadline - t - 1
			a_c = min(remain_time // a, remain_a)
			remain_time -= a_c * a
			b_c = min(remain_time // b, remain_b)
			ans = max(ans, i + a_c + b_c)
		t += needtime
		if needtime == a:
			remain_a -= 1
		else:
			remain_b -= 1
	if t <= T:
		ans = N
	print(ans)


t = int(input())
for _ in range(t):
	(n, T, a, b) = list(map(int, input().split(' ')))
	task_t = list(map(int, input().split(' ')))
	ness = list(map(int, input().split(' ')))
	perm = sorted(list(range(n)), key=lambda i: ness[i])
	score = 0
	tot_hard = sum(task_t)
	tot_easy = n - tot_hard
	must_easy = 0
	must_hard = 0
	for i in range(n):
		if i > 0 and ness[perm[i]] == ness[perm[i - 1]]:
			if task_t[perm[i]] == 0:
				must_easy += 1
			else:
				must_hard += 1
			continue
		tm = ness[perm[i]] - 1
		req_time = must_easy * a + must_hard * b
		if req_time > tm:
			if task_t[perm[i]] == 0:
				must_easy += 1
			else:
				must_hard += 1
			continue
		extra_time = tm - req_time
		extra_easy = min(extra_time // a, tot_easy - must_easy)
		extra_time -= a * extra_easy
		extra_hard = min(extra_time // b, tot_hard - must_hard)
		score = max(score, extra_easy + extra_hard + must_easy + must_hard)
		if task_t[perm[i]] == 0:
			must_easy += 1
		else:
			must_hard += 1
	if tot_easy * a + tot_hard * b <= T:
		score = n
	print(score)


m = int(input())
for _ in range(m):
	(n, T, a, b) = map(int, input().split())
	diff = list(map(int, input().split()))
	t = list(map(int, input().split()))
	problem = []
	for i in range(n):
		problem.append((diff[i], t[i]))
	problem.sort(key=lambda x: x[1])
	possible = [0] * (n + 1)
	easy_count = [0] * (n + 1)
	hard_count = [0] * (n + 1)
	easy = 0
	hard = 0
	pre_easy = 0
	pre_hard = 0
	for i in range(n):
		time = problem[i][1]
		difficulty = problem[i][0]
		stop = time - 1
		if i > 0 and problem[i - 1][1] != time:
			easy += pre_easy
			pre_easy = 0
			hard += pre_hard
			pre_hard = 0
		if easy * a + hard * b <= stop:
			possible[i] = 1
		if difficulty == 0:
			pre_easy += 1
		else:
			pre_hard += 1
		easy_count[i] = easy
		hard_count[i] = hard
	stop = T
	easy += pre_easy
	hard += pre_hard
	easy_count[n] = easy
	hard_count[n] = hard
	if easy * a + hard * b <= stop:
		possible[n] = 1
	ans = 0
	for i in range(n):
		count = 0
		if not possible[i]:
			continue
		time = problem[i][1] - 1
		spend = easy_count[i] * a + hard_count[i] * b
		count += easy_count[i] + hard_count[i]
		d = time - spend
		if (easy_count[n] - easy_count[i]) * a > d:
			count += d // a
		else:
			d -= (easy_count[n] - easy_count[i]) * a
			count += easy_count[n] - easy_count[i]
			if (hard_count[n] - hard_count[i]) * b > d:
				count += d // b
			else:
				count += hard_count[n] - hard_count[i]
		ans = max(ans, count)
	if possible[n]:
		count = 0
		i = n
		time = T
		spend = easy_count[i] * a + hard_count[i] * b
		count += easy_count[i] + hard_count[i]
		d = time - spend
		if (easy_count[n] - easy_count[i]) * a > d:
			count += d // a
		else:
			d -= (easy_count[n] - easy_count[i]) * a
			count += easy_count[n] - easy_count[i]
			if (hard_count[n] - hard_count[i]) * b > d:
				count += d // b
			else:
				count += hard_count[n] - hard_count[i]
		ans = max(ans, count)
	print(ans)


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

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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

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

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	(n, T, a, b) = value()
	hard = array()
	C = Counter(hard)
	t = array()
	total = [(t[i], hard[i]) for i in range(n)]
	total.append((-1, -1))
	total.sort()
	total.append((T + 1, inf))
	easy = 0
	hard = 0
	ans = 0
	for i in range(n + 1):
		(t, ty) = total[i]
		if ty == 1:
			hard += 1
		if ty == 0:
			easy += 1
		solved = hard + easy
		taken = hard * b + easy * a
		if taken >= total[i + 1][0]:
			continue
		if total[i + 1][0] > taken:
			rem = total[i + 1][0] - 1 - taken
			left = C[0] - easy
			solved_easy = min(rem // a, left)
			rem -= solved_easy * a
			solved_hard = min(rem // b, C[1] - hard)
			solved += solved_easy + solved_hard
		ans = max(ans, solved)
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, T, a, b) = map(int, input().split())
	ar = list(map(int, input().split()))
	tr = list(map(int, input().split()))
	br = []
	easy = 0
	hard = 0
	for i in range(n):
		if ar[i] == 0:
			easy += 1
			br.append([tr[i], a])
		else:
			hard += 1
			br.append([tr[i], b])
	br.sort(key=lambda x: x[0])
	su = []
	cou = 0
	for i in range(n):
		cou += br[i][1]
		su.append(cou)
	br.append([T + 1, 0])
	ans = 0
	ava_t = max(br[0][0] - 1, 0)
	xx = min(ava_t // a, easy)
	ava_t -= xx * a
	ans += xx
	xx = min(ava_t // b, hard)
	ans += xx
	for i in range(n):
		if br[i][1] == a:
			easy -= 1
		else:
			hard -= 1
		if br[i][0] == br[i + 1][0]:
			continue
		ava_t = br[i + 1][0] - 1
		if su[i] > ava_t:
			continue
		tem = i + 1
		ava_t -= su[i]
		tem_easy = easy
		tem_hard = hard
		xx = min(ava_t // a, tem_easy)
		ava_t -= xx * a
		tem += xx
		xx = min(ava_t // b, tem_hard)
		tem += xx
		ans = max(tem, ans)
	print(ans)


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 check(man, curt):
	global tez
	global thrd
	global a
	global b
	treq = man[0] * a + man[1] * b
	if treq > curt:
		points = 0
	else:
		points = man[0] + man[1]
		left = curt - treq
		v0 = min(left // a, tez - man[0])
		points += v0
		left -= v0 * a
		v1 = min(left // b, thrd - man[1])
		points += v1
	return points
import bisect
for j in range(int(input())):
	(n, t, a, b) = map(int, input().split())
	dif = list(map(int, input().split()))
	time = list(map(int, input().split()))
	dict1 = {}
	tez = 0
	thrd = 0
	for s in range(n):
		ez = 0
		hrd = 0
		if dif[s] == 0:
			ez += 1
		else:
			hrd += 1
		if not time[s] in dict1:
			dict1[time[s]] = (ez, hrd)
		else:
			tup = dict1[time[s]]
			dict1[time[s]] = (tup[0] + ez, tup[1] + hrd)
		tez += ez
		thrd += hrd
	both = []
	for s in dict1.keys():
		both.append((s, dict1[s]))
	both.sort(key=lambda x: x[0])
	for i in range(1, len(both)):
		bef = both[i - 1][1]
		both[i] = (both[i][0], (bef[0] + both[i][1][0], bef[1] + both[i][1][1]))
	maxpoints = 0
	for s in range(len(both)):
		mand = both[s]
		if s == 0 and mand[0] != 0:
			mand0 = (mand[0] - 1, (0, 0))
		elif mand[0] - 1 != both[s - 1][0]:
			mand0 = (mand[0] - 1, both[s - 1][1])
		points1 = check(mand[1], mand[0])
		points2 = check(mand0[1], mand0[0])
		maxpoints = max(maxpoints, points1, points2)
	if both[-1][0] != t:
		maxpoints = max(maxpoints, check(both[-1][1], t))
	print(maxpoints)


import os
from io import BytesIO, IOBase
import sys

def main():
	for _ in range(int(input())):
		(n, T, a, b) = map(int, input().split())
		diff = list(map(int, input().split()))
		time = list(map(int, input().split()))
		time.append(T)
		diff.append(2)
		c = sorted(range(n + 1), key=lambda x: time[x])
		(ma, su, e, h) = (0, 0, diff.count(0), diff.count(1))
		for (j, i) in enumerate(c):
			t = time[i] - (diff[i] != 2) - su
			z = min(e, t // a)
			y = min((t - z * a) // b, h)
			t -= y * b
			ma = max(ma, z + y + j * (t >= 0))
			if diff[i] == 1:
				(su, h) = (su + b, h - 1)
			elif diff[i] == 0:
				(su, e) = (su + a, e - 1)
			else:
				break
			if su > T:
				break
		print(ma)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


from bisect import bisect_left as bl
from bisect import bisect_right as br
from collections import *
import sys
input = sys.stdin.readline

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

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

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n').split(' ')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
for _ in range(val()):
	(n, T, A, B) = li()
	level = li()
	time = li()
	ques = [[i, j] for (i, j) in zip(level, time)]
	(tota, totb) = (0, 0)
	for i in ques:
		if i[0]:
			totb += 1
		else:
			tota += 1
	ques.sort(key=lambda x: x[1])
	mandatory = {}
	prev = [0, 0]
	for i in range(n):
		prev[ques[i][0]] += 1
		mandatory[ques[i][1]] = tuple(prev)
	mandatory[T] = tuple(prev)
	if 0 not in mandatory:
		mandatory[0] = tuple([0, 0])
	timemandatory = sorted(list(mandatory))
	for i in range(1, len(timemandatory)):
		if timemandatory[i] - 1 not in mandatory:
			mandatory[timemandatory[i] - 1] = mandatory[timemandatory[i - 1]]
	timemandatory = sorted(list(mandatory))
	ans = 0
	for i in timemandatory:
		if i >= 0:
			rema = tota - mandatory[i][0]
			remb = totb - mandatory[i][1]
			remtime = i - (mandatory[i][0] * A + mandatory[i][1] * B)
			curr = sum(mandatory[i])
			if remtime >= 0:
				more = min(remtime // A, rema)
				remtime -= A * min(remtime // A, rema)
				more += min(remtime // B, remb)
				ans = max(ans, more + curr)
	print(ans)


import sys
t = int(sys.stdin.readline())
for _ in range(t):
	(n, time, a, b) = map(int, sys.stdin.readline().split())
	nums = list(map(int, sys.stdin.readline().split()))
	l = list(map(int, sys.stdin.readline().split()))
	(easy, hard, ans) = (0, 0, 0)
	for i in range(n):
		if nums[i] == 0:
			l[i] = [l[i], 0]
			easy += 1
		else:
			l[i] = [l[i], 1]
			hard += 1
	l.sort()
	(count_easy, count_hard) = (0, 0)
	(easy_man, hard_man) = (0, 0)
	for i in range(n):
		count = 0
		t = l[i][0] - 1
		if a * easy_man + b * hard_man <= t:
			count += easy_man + hard_man
			t -= a * easy_man + b * hard_man
			(easy_rem, hard_rem) = (easy - easy_man, hard - hard_man)
			if easy_rem * a > t:
				count += t // a
			else:
				count += easy_rem
				t -= a * easy_rem
				if hard_rem * b > t:
					count += t // b
				else:
					count += hard_rem
		if l[i][1] == 1:
			hard_man += 1
		else:
			easy_man += 1
		ans = max(ans, count)
	if 1 == 1:
		count = 0
		t = time
		if a * easy_man + b * hard_man <= t:
			count += easy_man + hard_man
			t -= a * easy_man + b * hard_man
			(easy_rem, hard_rem) = (easy - easy_man, hard - hard_man)
			if easy_rem * a > t:
				count += t // a
			else:
				count += easy_rem
				t -= a * easy_rem
				if hard_rem * b > t:
					count += t // b
				else:
					count += hard_rem
		if l[i][1] == 1:
			hard_man += 1
		else:
			easy_man += 1
	ans = max(ans, count)
	print(ans)


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 sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z
for ir in range(int(input())):
	(n, T, a, b) = map(int, input().split())
	e = list(map(int, input().split()))
	w = list(map(int, input().split()))
	e = sort_list(e, w)
	w.sort()
	tote = e.count(0)
	toth = n - tote
	easy = 0
	hard = 0
	ma = 0
	for i in range(n):
		if w[i] != 0:
			t = w[i] - 1
			t -= easy * a + hard * b
			if t < 0:
				ans = 0
			else:
				y = min(tote - easy, t // a)
				t -= y * a
				r = min(toth - hard, t // b)
				ans = easy + y + (hard + r)
				ma = max(ma, ans)
		if e[i] == 0:
			easy += 1
		else:
			hard += 1
		if i != n - 1 and w[i] == w[i + 1]:
			continue
		t = w[i]
		t -= easy * a + hard * b
		if t < 0:
			ans = 0
		else:
			y = min(tote - easy, t // a)
			t -= y * a
			r = min(toth - hard, t // b)
			ans = easy + y + (hard + r)
			ma = max(ma, ans)
	t = T
	t -= easy * a + hard * b
	if t < 0:
		ans = 0
	else:
		y = min(tote - easy, t // a)
		t -= y * a
		r = min(toth - hard, t // b)
		ans = easy + y + (hard + r)
		ma = max(ma, ans)
	print(ma)


deadline = int(input())
for _ in range(deadline):
	(n, T, a, b) = map(int, input().split())
	hard = list(map(int, input().split()))
	time = [b if h else a for h in hard]
	easies = n - sum(hard)
	deadlines = list(map(int, input().split()))
	tasks = [(deadlines[i], i) for i in range(n)]
	tasks.sort()
	filled_until = 0
	max_pts = 0
	done = 0
	curr = 0
	for (deadline, i) in tasks:
		if deadline > filled_until:
			if hard[i]:
				before = (deadline - filled_until - 1) // a
				max_pts = max(max_pts, done + min(easies, before))
			else:
				max_pts = max(max_pts, done)
		filled_until += time[i]
		done += 1
		if not hard[i]:
			easies -= 1
	if filled_until <= T:
		max_pts = n
	print(max_pts)


import bisect
t = int(input())
for you in range(t):
	l = input().split()
	n = int(l[0])
	T = int(l[1])
	a = int(l[2])
	b = int(l[3])
	l = input().split()
	eorh = [int(i) for i in l]
	totofh = sum(eorh)
	totofe = n - totofh
	l = input().split()
	timeofenter = [int(i) for i in l]
	lfi = []
	for i in range(n):
		lfi.append((timeofenter[i], eorh[i]))
	lfi.sort()
	lfi.append((T, -1))
	numofe = 0
	numofh = 0
	maxa = 0
	for i in range(n + 1):
		if i != n:
			timenow = lfi[i][0] - 1
		else:
			timenow = lfi[i][0]
		count = 0
		if a * numofe + b * numofh <= timenow:
			count += numofe + numofh
			timeextra = timenow - (a * numofe + b * numofh)
			if numofe < totofe:
				if timeextra <= (totofe - numofe) * a:
					count += timeextra // a
				else:
					count += totofe - numofe
					timeextra -= (totofe - numofe) * a
					if numofh < totofh:
						if timeextra <= (totofh - numofh) * b:
							count += timeextra // b
						else:
							count += totofh - numofh
			elif numofh < totofh:
				if timeextra <= (totofh - numofh) * b:
					count += timeextra // b
				else:
					count += totofh - numofh
			if count > maxa:
				maxa = count
		if lfi[i][1] == 1:
			numofh += 1
		elif lfi[i][1] == 0:
			numofe += 1
	print(maxa)


import sys
from collections import defaultdict
reader = (map(int, line.split()) for line in sys.stdin)

def func(n, TIME, a, b, lvl, deadline):
	schedule = defaultdict(list)
	for (task, time) in enumerate(deadline):
		schedule[time].append(task)
	timeline = [t for t in schedule.keys()]
	timeline += [t - 1 for t in timeline]
	timeline.append(0)
	timeline.append(T)
	timeline = set(timeline)
	timeline.discard(-1)
	timeline = sorted(timeline)
	hard = sum(lvl)
	easy = n - hard
	D = {0: 0}
	mustDo = {0: [0, 0]}
	for task in schedule[0]:
		if lvl[task]:
			D[0] += b
			mustDo[0][1] += 1
		else:
			D[0] += a
			mustDo[0][0] += 1
	for i in range(1, len(timeline)):
		t = timeline[i]
		t_prev = timeline[i - 1]
		D[t] = D[t_prev]
		mustDo[t] = mustDo[t_prev].copy()
		for task in schedule[t]:
			if lvl[task]:
				D[t] += b
				mustDo[t][1] += 1
			else:
				D[t] += a
				mustDo[t][0] += 1
	maxScore = 0
	for t in timeline:
		if D[t] > t:
			continue
		score = sum(mustDo[t])
		extra = t - D[t]
		easy_left = easy - mustDo[t][0]
		hard_left = hard - mustDo[t][1]
		if extra // a < easy_left:
			score += extra // a
			maxScore = max(maxScore, score)
		else:
			score += easy_left
			extra -= a * easy_left
			score += min(hard_left, extra // b)
			maxScore = max(maxScore, score)
	return maxScore
(m,) = next(reader)
for _ in range(m):
	(n, T, a, b) = next(reader)
	lvl = list(next(reader))
	deadline = list(next(reader))
	ans = func(n, T, a, b, lvl, deadline)
	print(ans)


from collections import deque
import sys
import math
input = sys.stdin.buffer.readline
q = int(input())
for _ in range(q):
	(n, timetotal, a, b) = map(int, input().split())
	prob = []
	dif = list(map(int, input().split()))
	tees = list(map(int, input().split()))
	easy = dif.count(0)
	hard = n - easy
	for i in range(n):
		prob.append((tees[i] - 1, dif[i]))
	prob.sort()
	htosol = 0
	etosol = 0
	ans = []
	bad = False
	for p in prob:
		tt = p[0]
		tt -= etosol * a + htosol * b
		if tt > -1:
			ezsolved = min(tt // a, easy - etosol)
			remain = tt - ezsolved * a
			hardsolved = min(hard - htosol, remain // b)
			ans.append(ezsolved + etosol + hardsolved + htosol)
		if p[1] == 0:
			etosol += 1
		else:
			htosol += 1
	if not bad:
		p = [timetotal, 0]
		tt = p[0]
		tt -= etosol * a + htosol * b
		if tt > -1:
			ezsolved = min(tt // a, easy - etosol)
			remain = tt - ezsolved * a
			hardsolved = min(hard - htosol, remain // b)
			ans.append(ezsolved + etosol + hardsolved + htosol)
	if ans:
		print(max(ans))
	else:
		print(0)


from math import *
from collections import *
import sys
sys.setrecursionlimit(10 ** 9)
m = int(input())
for y in range(m):
	(n, t, a, b) = map(int, input().split())
	c = list(map(int, input().split()))
	A = c.count(0)
	d = list(map(int, input().split()))
	l = []
	T = [0 for i in range(n)]
	aa = [A for i in range(n)]
	for i in range(n):
		l.append([d[i], c[i]])
	l.sort()
	for i in range(n):
		if l[i][1] == 0:
			if i == 0:
				T[i] = a
				aa[i] = A - 1
			else:
				T[i] = T[i - 1] + a
				aa[i] = aa[i - 1] - 1
		else:
			if i == 0:
				T[i] = b
			else:
				T[i] = T[i - 1] + b
			aa[i] = aa[i - 1]
	ct = max(min(A, (l[0][0] - 1) // a), 0)
	for i in range(n):
		if i == n - 1:
			if T[i] <= t:
				ct = max(ct, i + 1)
		elif T[i] < l[i + 1][0]:
			ct1 = (l[i + 1][0] - 1 - T[i]) // a
			ct1 = min(ct1, aa[i])
			ct = max(ct, i + 1 + ct1)
	print(ct)


class questions:

	def __init__(self, level, req_time):
		self.level = level
		self.Ti = req_time
for _ in range(int(input())):
	(n, N, a, b) = map(int, input().split())
	level = list(map(int, input().split()))
	Ti = list(map(int, input().split()))
	easy_q = level.count(0)
	hard_q = level.count(1)
	ql = []
	for i in range(n):
		ql.append(questions(level[i], Ti[i]))
	ql.sort(key=lambda x: x.Ti)
	req_time = 0
	solved_easy = 0
	solved_hard = 0
	best_point = 0
	last_t_leave = 0
	last_idx = 0
	for i in range(n + 1):
		if i == n:
			t_leave = N
		else:
			t_leave = ql[i].Ti - 1
		if t_leave == last_t_leave:
			continue
		last_t_leave = t_leave
		points = 0
		for j in range(last_idx, i):
			if ql[j].level == 0:
				solved_easy += 1
				req_time += a
			else:
				solved_hard += 1
				req_time += b
		last_idx = i
		if req_time <= t_leave:
			points += solved_easy + solved_hard
			available_time = t_leave - req_time
			pos_easy = int(available_time / a)
			other_easy = min(pos_easy, easy_q - solved_easy)
			points += other_easy
			available_time -= other_easy * a
			pos_hard = int(available_time / b)
			other_hard = min(pos_hard, hard_q - solved_hard)
			points += other_hard
		else:
			points = 0
		best_point = max(best_point, points)
	print(best_point)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
	(n, t, a, b) = map(int, input().split())
	qtype = list(map(int, input().split()))
	time = list(map(int, input().split()))
	times = []
	maxa = 0
	for i in range(n):
		times.append([time[i], qtype[i]])
		if qtype[i] == 0:
			maxa += 1
	acount = 0
	bcount = 0
	ans = 0
	times = sorted(times, key=lambda student: student[0])
	for i in range(n):
		currenttime = times[i][0] - 1
		if currenttime < 0:
			if times[i][1] == 0:
				acount += 1
			else:
				bcount += 1
			continue
		if acount * a + bcount * b > currenttime:
			if times[i][1] == 0:
				acount += 1
			else:
				bcount += 1
			continue
		currenttime -= acount * a + bcount * b
		tmp = acount + bcount
		if currenttime > a * (maxa - acount):
			tmp += maxa - acount
			currenttime -= a * (maxa - acount)
			tmp += currenttime // b
		else:
			tmp += currenttime // a
		ans = max(tmp, ans)
		if times[i][1] == 0:
			acount += 1
		else:
			bcount += 1
	if maxa * a + (n - maxa) * b <= t:
		ans = n
	print(ans)


def case():
	(n, t, a, b) = map(int, input().split())
	qtype = list(map(int, input().split()))
	qtime = list(map(int, input().split()))
	z = []
	(easy, hard) = (0, 0)
	for i in range(n):
		easy += qtype[i] == 0
		hard += qtype[i] == 1
		z.append([qtime[i], qtype[i]])
	z.sort()
	ans = 0
	(esol, hsol) = (0, 0)
	for i in z:
		if esol * a + hsol * b < i[0]:
			trem = i[0] - a * esol - b * hsol - 1
			exe = min(easy - esol, trem // a)
			trem -= exe * a
			exh = min(hard - hsol, trem // b)
			ans = max(hsol + esol + exe + exh, ans)
		if i[1] == 0:
			esol += 1
		else:
			hsol += 1
	if esol * a + hsol * b <= t:
		trem = t - a * esol - b * hsol
		exe = min(easy - esol, trem // a)
		trem -= exe * a
		exh = min(hard - hsol, trem // b)
		ans = max(hsol + esol + exe + exh, ans)
	print(ans)
for _ in range(int(input())):
	case()


for _ in range(int(input())):
	(n, T, A, B) = list(map(int, input().split(' ')))
	level = list(map(int, input().split(' ')))
	time = list(map(int, input().split(' ')))
	ques = [[i, j] for (i, j) in zip(level, time)]
	(tota, totb) = (0, 0)
	for i in ques:
		if i[0]:
			totb += 1
		else:
			tota += 1
	ques.sort(key=lambda x: x[1])
	mandatory = {}
	prev = [0, 0]
	for i in range(n):
		prev[ques[i][0]] += 1
		mandatory[ques[i][1]] = tuple(prev)
	mandatory[T] = tuple(prev)
	if 0 not in mandatory:
		mandatory[0] = tuple([0, 0])
	timemandatory = sorted(list(mandatory))
	for i in range(1, len(timemandatory)):
		if timemandatory[i] - 1 not in mandatory:
			mandatory[timemandatory[i] - 1] = mandatory[timemandatory[i - 1]]
	timemandatory = sorted(list(mandatory))
	ans = 0
	for i in timemandatory:
		if i >= 0:
			rema = tota - mandatory[i][0]
			remb = totb - mandatory[i][1]
			remtime = i - (mandatory[i][0] * A + mandatory[i][1] * B)
			curr = sum(mandatory[i])
			if remtime >= 0:
				more = min(remtime // A, rema)
				remtime -= A * min(remtime // A, rema)
				more += min(remtime // B, remb)
				ans = max(ans, more + curr)
	print(ans)


for _ in range(int(input())):
	(n, T, a, b) = map(int, input().split())
	diff = list(map(int, input().split()))
	time = list(map(int, input().split()))
	alla = diff.count(0)
	allb = n - alla
	prob = list(zip(time, diff))
	prob.sort()
	cnt = 0
	sm = 0
	hard_x = 0
	easy_x = 0

	def calc(time):
		points = hard_x + easy_x
		time -= hard_x * b + easy_x * a
		a_avail = alla - easy_x
		b_avail = allb - hard_x
		dp = min(a_avail, time // a)
		points += dp
		time -= dp * a
		return points + min(b_avail, time // b)
	for pr in prob:
		if pr[0] > easy_x * a + hard_x * b:
			cnt = max(cnt, calc(pr[0] - 1))
		if pr[1] == 1:
			hard_x += 1
		else:
			easy_x += 1
	if alla * a + allb * b <= T:
		cnt = max(cnt, calc(T))
	print(cnt)