#include using namespace std; using int64 = long long; using i128 = __int128_t; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int N; long long K; cin >> N >> K; vector A(N), B(N), C(N), D(N); for (int i = 0; i < N; i++) cin >> A[i]; for (int i = 0; i < N; i++) cin >> B[i]; for (int i = 0; i < N; i++) cin >> C[i]; for (int i = 0; i < N; i++) cin >> D[i]; // key = buy cost, value = count of stored jewels with that cost map mp; long long total = 0; // total stored jewels i128 ans = 0; // profit over initial 10^100 for (int i = 0; i < N; i++) { // 1) Buy candidates mp[A[i]] += B[i]; total += B[i]; // 2) Sell up to D[i], always from cheapest profitable jewels long long remSell = D[i]; while (remSell > 0 && !mp.empty()) { auto it = mp.begin(); long long cost = it->first; long long cnt = it->second; if (cost >= C[i]) break; // no profitable sell anymore long long x = min(remSell, cnt); ans += (i128)x * (C[i] - cost); remSell -= x; total -= x; it->second -= x; if (it->second == 0) mp.erase(it); } // 3) Keep only cheapest K jewels for future; discard expensive extras long long excess = total - K; while (excess > 0) { auto it = prev(mp.end()); long long cnt = it->second; long long x = min(excess, cnt); it->second -= x; total -= x; excess -= x; if (it->second == 0) mp.erase(it); } } // print i128 if (ans == 0) { cout << 0 << '\n'; } else { string s; while (ans > 0) { int digit = (int)(ans % 10); s.push_back(char('0' + digit)); ans /= 10; } reverse(s.begin(), s.end()); cout << s << '\n'; } } return 0; }