题意
题解
参考动态维护中位数的对顶堆算法,可以得到 O ( ( N + M ) log M ) O((N+M)\log M) O((N+M)logM) 的算法。使用一个大根堆维护 [ 1 , i ] [1,i] [1,i] 的元素,使用一个小根堆维护剩余元素,离线地处理即可。
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 30005;
int M, N, A[maxn], cnt[maxn];
priority_queue<int> L;
priority_queue<int, vector<int>, greater<int>> R;
int main()
{
scanf("%d%d", &M, &N);
for (int i = 1; i <= M; ++i)
scanf("%d", A + i);
for (int i = 1, q; i <= N; ++i)
scanf("%d", &q), ++cnt[q];
for (int i = 1; i <= M; ++i)
{
if (L.size() && A[i] > L.top())
R.push(A[i]);
else
L.push(A[i]), R.push(L.top()), L.pop();
while (cnt[i]--)
L.push(R.top()), R.pop(), printf("%d\n", L.top());
}
return 0;
}