Handling Array Queries with Sorting and a Running Subtraction

Published:

The key idea is to combine a greedy strategy with direct simulation of the query process.

First, sort the array in ascending order. After sorting, locate the first position idx where a[idx] != 0. Elements before this position are already zero and do not need to be considered.

For each query, use a variable base to record the total value that has already been subtracted from the array. When checking the current element, the real value after previous operations is not a[idx], but:

a[idx] - base

If a[idx] - base > 0, it means the current element is still positive after all previous reductions. This value should be printed, and then the same amount is considered subtracted from all remaining elements. Therefore, add a[idx] - base to base.

If a[idx] - base == 0, the current element has already become zero after earlier operations. In that case, move idx forward until reaching an element that is still non-zero after subtracting base.

Because the array has been sorted, the greedy process is valid: for any current position, the remaining values satisfy:

a[idx] - base <= a[idx + 1] - base

So once the current element becomes zero, all earlier elements can be skipped permanently. When idx can no longer move to a valid element, it means every element in the array has become zero after the performed operations.

Code:

#include <bits/stdc++.h>
using namespace std;

const int N = 1e6 + 3;

int a[N];

void solve(){
    int n, k; cin >> n >> k;
    for(int i = 0; i < n; i ++) cin >> a[i];
    sort(a, a + n);
    int idx = 0; while(a[idx] == 0 && idx < n) idx ++;  // 找到第一个 a[idx] != 0 的位置
    int base = 0;
    while(k --){
        while(a[idx] - base == 0 && idx < n) idx ++;  // 找到此次询问 a[idx] != 0 的位置
        if(a[idx] - base > 0){
            cout << a[idx] - base << endl;  // 输出经过操作后的值,即 a[idx] - base
            base += a[idx] - base;  // 将剩余的 a[idx] - base 加和到 base 中,后续操作需要减去当前操作的值
        }
        else cout << 0 << endl;
    }
}

int main(){
    solve();
    return 0;
}