洛谷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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章