import sys import heapq from collections import defaultdict def main(): data = sys.stdin.buffer.read().split() idx = 0 T = int(data[idx]); idx += 1 out = [] for _ in range(T): N = int(data[idx]); idx += 1 K = int(data[idx]); idx += 1 A = [int(x) for x in data[idx:idx+N]]; idx += N B = [int(x) for x in data[idx:idx+N]]; idx += N C = [int(x) for x in data[idx:idx+N]]; idx += N D = [int(x) for x in data[idx:idx+N]]; idx += N min_h, max_h = [], [] cnt = defaultdict(int) total = 0 profit = 0 for i in range(N): a, b, c, d = A[i], B[i], C[i], D[i] if cnt[a] == 0: heapq.heappush(min_h, a) heapq.heappush(max_h, -a) cnt[a] += b total += b rem = d while rem > 0: while min_h and cnt[min_h[0]] == 0: heapq.heappop(min_h) if not min_h: break p = min_h[0] if p >= c: break take = cnt[p] if cnt[p] < rem else rem profit += (c - p) * take cnt[p] -= take if cnt[c] == 0: heapq.heappush(min_h, c) heapq.heappush(max_h, -c) cnt[c] += take rem -= take while total > K: while max_h and cnt[-max_h[0]] == 0: heapq.heappop(max_h) if not max_h: break p = -max_h[0] need = total - K drop = cnt[p] if cnt[p] < need else need cnt[p] -= drop total -= drop out.append(str(profit)) sys.stdout.write('\n'.join(out) + '\n') main()