传送门
解题思路:用一个大顶堆维护前k小元素,查询那就把堆顶输出就好了,再用一个小顶堆维护其他的比较大的值(小顶堆中的值都大于大顶堆的值),因为k是变化的,每次值先放进小顶堆,如果大顶堆的size<k,那就用小堆顶填大顶堆直到它的size==k,其次当小顶堆堆顶的值小于大顶堆堆顶时,也需要更新。STL中实现好的堆heap
#include<bits/stdc++.h>
#define il inline
#define pb push_back
#define fi first
#define se second
#define ms(_data,v) memset(_data,v,sizeof(_data))
using namespace std;
typedef long long ll;
const ll inf=0x3f3f3f3f;
const int maxn=2e5+5;
int n,m;
vector<int> mx,mi;
int a[maxn],u[maxn];
bool cmp(int x,int y){return x<y;}
int main(){
std::ios::sync_with_stdio(0);
cin>>m>>n;
for(int i=1;i<=m;++i) cin>>a[i];
for(int j=1;j<=n;++j) cin>>u[j];
int qu=1;
make_heap(mx.begin(),mx.end()); //大堆
make_heap(mi.begin(),mi.end(),greater<int>()); //小堆
for(int i=1;i<=m;++i){
if((int)mx.size()==0) mx.pb(a[i]),push_heap(mx.begin(),mx.end());
else{
mi.pb(a[i]),push_heap(mi.begin(),mi.end(),greater<int>());
while((int)mx.size()<qu && mi.size()!=0){
mx.pb(mi.front()),push_heap(mx.begin(),mx.end());
pop_heap(mi.begin(),mi.end(),greater<int>()),mi.pop_back();
}
if(mi.size()!=0 && mx.front()>mi.front()){
int nmx=mx.front(),nmi=mi.front();
pop_heap(mx.begin(),mx.end()),mx.pop_back();
pop_heap(mi.begin(),mi.end(),greater<int>()),mi.pop_back();
mx.pb(nmi),push_heap(mx.begin(),mx.end());
mi.pb(nmx),push_heap(mi.begin(),mi.end(),greater<int>());
}
}
while(i==u[qu]){
cout<<mx.front()<<endl;
qu++;
if(u[qu]==i){
mx.pb(mi.front()),push_heap(mx.begin(),mx.end());
pop_heap(mi.begin(),mi.end(),greater<int>()),mi.pop_back();
}
}
}
return 0;
}