P1801: Black Box — Solution
Main Idea
We can consider a godlike structure: the two-heap structure. Create a max-heap \(qmax\) and a min-heap \(qmin\). We first store the data in an array. Then, for a given query, we need to find, among the first \(u(i)\) numbers of the whole sequence, the \(i\)-th smallest number. At each query, we put the first \(u(i)\) numbers into the max-heap, and when the number of elements in the max-heap equals \(i\), we move the largest number in the max-heap (the heap top) into the min-heap. In the end, the max-heap holds \(i-1\) elements, and the \(i\)-th smallest number we are looking for must be at the top of the min-heap.
Why? Because each time we move the top of the max-heap into the min-heap, which means every number in the min-heap is greater than every number in the max-heap. Then the max-heap maintains \(i-1\) numbers, so the \(i\)-th largest number is naturally at the top of the min-heap.
Code
// P1801.cpp
#include <iostream>
#include <cstdio>
#include <queue>
#define ll long long
using namespace std;
const int maxn = 210000;
ll M, N, arr[maxn], num, idx = 0, r = 1;
priority_queue<ll> qmax;
priority_queue< ll, vector<ll>, greater<ll> > qmin;
int main()
{
scanf("%lld%lld", &M, &N);
for (int i = 1; i <= M; i++)
scanf("%lld", &arr[i]);
for (int i = 1; i <= N; i++)
{
scanf("%lld", &num), idx++;
for (int prev = r; prev <= num; prev++)
{
qmax.push(arr[prev]);
if (i == qmax.size())
qmin.push(qmax.top()), qmax.pop();
}
r = num + 1;
printf("%d\n", qmin.top()), qmax.push(qmin.top()), qmin.pop();
}
return 0;
}