// Problem: E. Binary Wine // Contest: Codeforces - Codeforces Round 1064 (Div. 2) // URL: https://codeforces.com/contest/2166/problem/E // Memory Limit: 512 MB // Time Limit: 2000 ms // // Powered by CP Editor (https://cpeditor.org) #include #include using namespace std; #ifndef __DEBUG__ #define dbg(...) 42 #endif template using mpq = priority_queue, greater>; namespace rngs = std::ranges; using ll = long long; using a2l = array; using vl = vector; void solve() { ll n, q; cin >> n >> q; vl a(n); for (auto &x : a) cin >> x; priority_queue pq; for (auto x : a) pq.push({x, 1}); // priority_queue pq(a.begin(), a.end()); multiset add; multiset del; for (ll i = 0, c; i < q; ++i) { cin >> c; for (auto x : add) pq.push({x, 1}); add.clear(); dbg(c); bool done = false; ll cost = 0; for (ll j = 30; j >= 0 && !done; --j) { auto [val, ori] = pq.top(); while (del.contains({val, ori})) { pq.pop(); del.extract({val, ori}); std::tie(val, ori) = pq.top(); // val = pq.top()[0], ori = pq.top()[1]; } if (c <= val) { done = true; cout << cost << '\n'; break; } ll b = (c >> j) % 2; if (b) { ll tg = 1ll << j; dbg(cost, tg, val); ll dc = 0; del.insert({val, ori}); if (tg >= val) { dc = tg - val; pq.push({0, 0}); if (ori) add.insert(val); } else { dc = 0; pq.push({min(tg - 1, val - tg), 0}); if (ori) add.insert(val); } dbg(tg, val, dc); cost += dc; c -= tg; } } if (!done) cout << cost << '\n'; } } int main(int argc, char **argv) { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); ll t = 1; cin >> t; while (t--) solve(); return 0; };