rt,我使用对顶堆解决该题,思路参见P1168第二篇由 肖恩Sean 发布的题解
这是第一版代码,WA
#include <bits/stdc++.h>
#define ll long long
using namespace std;
int a[200005],cnt=0;int gt[200005];
priority_queue<int> mi;
priority_queue<int,vector<int>,greater<int> > ma;
inline ll read(){
ll ref=0,f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-') f=-1;ch=getchar();}
while(isdigit(ch)) ref=(ref<<1)+(ref<<3)+ch-48,ch=getchar();
return ref*f;
}
int main(){
int n=read(),m=read();
for(int i=0;i<n;i++) a[i]=read();
for(int i=0;i<m;i++) gt[read()]++;
for(int i=0;i<n;i++){
if(mi.empty()||a[i]<=mi.top()) mi.push(a[i]);
else if(a[i]>mi.top()) ma.push(a[i]);
while(gt[i+1]--){
cnt++;
while(mi.size()>cnt){ma.push(mi.top());mi.pop();}
while(mi.size()<cnt){mi.push(ma.top());ma.pop();}
cout<<mi.top()<<endl;
}
while(mi.size()>cnt) ma.push(mi.top()),mi.pop();
while(mi.size()<cnt) mi.push(ma.top()),ma.pop();
}
return 0;
}
这是第二版代码,AC
#include <bits/stdc++.h>
#define ll long long
using namespace std;
int a[200005],cnt=0;int gt[200005];
priority_queue<int> mi;
priority_queue<int,vector<int>,greater<int> > ma;
inline ll read(){
ll ref=0,f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-') f=-1;ch=getchar();}
while(isdigit(ch)) ref=(ref<<1)+(ref<<3)+ch-48,ch=getchar();
return ref*f;
}
int main(){
int n=read(),m=read();
for(int i=0;i<n;i++) a[i]=read();
for(int i=0;i<m;i++) gt[read()]++;
for(int i=0;i<n;i++){
if(mi.empty()||a[i]<=mi.top()) mi.push(a[i]);
else if(a[i]>mi.top()) ma.push(a[i]);
while(gt[i+1]--){
cnt++;
while(mi.size()>cnt){ma.push(mi.top());mi.pop();}
while(mi.size()<cnt){mi.push(ma.top());ma.pop();}
cout<<mi.top()<<endl;
}
}
return 0;
}
很明显,区别在于删除了26~27行