(Luogu) P1801 黑匣子_NOI导刊2010提高(06)(堆)

传送门

解题思路:用一个大顶堆维护前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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值