洛谷P1801 黑匣子 堆

题目链接:https://www.luogu.com.cn/problem/P1801

本题用一个小根堆,一个大根堆即可解决。
每有一个新元素,将它和大根堆的堆顶进行比较,如果比它小,将它放入大根堆,并把大根堆堆顶放入小根堆。如果比它大,直接将其放入小根堆。如果这次有GET命令,就输出小根堆堆顶元素,并将其拿出放入大根堆。
代码如下(用的优先队列)

#include <bits/stdc++.h>
using namespace std;
priority_queue<int,vector<int>,greater<int> >q1;//小的优先
priority_queue<int>q2;//大的优先
const int maxn=2e5+5;
int a[maxn];
int cnt[maxn];//记录第几个数有GET命令
int n,m,x;
int main()
{
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++)
    scanf("%d",&a[i]);
    for(int i=1;i<=m;i++)
    {
        scanf("%d",&x);
        cnt[x]++;
    }
    for(int i=1;i<=n;i++)
    {
        if(!q2.empty())
        {
            int top=q2.top();
            if(a[i]<top)
            q2.pop(),q2.push(a[i]),q1.push(top);
            else
            q1.push(a[i]);
        }
        else
        q1.push(a[i]);
        for(int j=1;j<=cnt[i];j++)
        {
            int x=q1.top();
            printf("%d\n",x);
            q1.pop();
            q2.push(x);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值