// UUID: aaa0a5cc-2d2b-4154-ae92-a342ef80dbb7
#include <iostream>
#include <vector>
// Using global arrays as in the original code.
const int MAX_N = 1e5 + 5; // A little extra buffer is safe practice
int a[MAX_N];
int f[MAX_N];
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
int n, k;
std::cin >> n >> k;
for (int i = 0; i < n; ++i) {
std::cin >> a[i];
}
// This vector will store a list of every index in `f` that we modify.
std::vector<int> indices_to_clear;
for (; k > 0; --k) {
// --- FAST RESET ---
// Instead of clearing all 1...N, only clear what was touched in the last query.
for (int index : indices_to_clear) {
f[index] = 0;
}
indices_to_clear.clear();
int p;
std::cin >> p;
// --- Populate the frequency array and track indices ---
for (int i = 0; i < p; ++i) {
if (f[a[i]] == 0) { // If this is the first time we see this card value...
indices_to_clear.push_back(a[i]); // ...track it for the next cleanup.
}
f[a[i]]++;
}
int mx = n; // The rest of the logic is IDENTICAL to your original code
int pocket = 0;
int player = 1;
long long score = 0;
// --- Loop 1 ---
for (int i = p; i < n; ++i, player *= -1) {
if (pocket) {
score += (long long)pocket * player;
pocket = 0;
} else {
while (!f[mx]) {
mx--;
}
f[mx]--;
score += (long long)mx * player;
}
if (a[i] <= mx) {
// When adding a card back, we must also track its index for cleanup
if (f[a[i]] == 0) {
indices_to_clear.push_back(a[i]);
}
f[a[i]]++;
} else {
pocket = a[i];
}
}
// --- Loop 2 ---
for (int i = 0; i < p; ++i, player *= -1) {
if (pocket) {
score += (long long)pocket * player;
pocket = 0;
} else {
// In this part of the original code, you only ever remove cards,
// so we don't need to add to indices_to_clear here.
if (mx > 0) { // Small optimization to prevent mx from going to 0 or below if f is empty
while (mx > 0 && !f[mx]) {
mx--;
}
if (mx > 0 || f[mx] > 0) { // Ensure we found a valid card
f[mx]--;
score += (long long)mx * player;
}
}
}
}
std::cout << score << '\n';
}
return 0;
}