#include #include #include #include using namespace std; void solve() { 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]; // Map stores {cost: count_of_jewels_available_at_this_cost} map pq; long long total_items = 0; long long profit = 0; for (int i = 0; i < N; i++) { // 1. Add up to B[i] buying options if (B[i] > 0) { pq[A[i]] += B[i]; total_items += B[i]; } // 2. Greedily sell up to D[i] items at price C[i] long long to_sell = D[i]; long long fake_buys = 0; while (to_sell > 0 && !pq.empty()) { auto it = pq.begin(); long long cost = it->first; long long count = it->second; // Stop if the cheapest available cost is strictly greater or equal to selling price if (cost >= C[i]) { break; } long long take = min(to_sell, count); profit += take * (C[i] - cost); fake_buys += take; to_sell -= take; it->second -= take; if (it->second == 0) { pq.erase(it); } } // Add back fake buys to allow future upgrading of the sales prices if (fake_buys > 0) { pq[C[i]] += fake_buys; // Notice total_items doesn't increase here because the fake_buys // directly replace the actual buys we pulled out above. } // 3. Ensure we don't violate the storage capacity constraint K while (total_items > K) { auto it = prev(pq.end()); // Look at the elements with the highest cost long long count = it->second; long long remove_cnt = min(total_items - K, count); total_items -= remove_cnt; it->second -= remove_cnt; if (it->second == 0) { pq.erase(it); } } } cout << profit << "\n"; } int main() { // Fast I/O ios_base::sync_with_stdio(false); cin.tie(NULL); int T; if (cin >> T) { while (T--) { solve(); } } return 0; }