题意:
三种操作:
- 在 A 序列的末尾添加一个元素 X
- 输出 A 中第一个元素并删除
- 对 A 序列进行排序
思路
首先,我们可以想到可以使用优先队列,但是不能只用优先队列,我们不能加入一个元素就直接压到优先队列里面去。
我们可以用数组模拟一个普通的队列,hh 表示队头,tt 表示队尾
可以进行一下操作:
一开始先将元素加入到普通的队列中,当我们收到的操作是排序的话,我们就将所有的元素全部压到优先队列里面,然后清空我们的普通队列,令
hh = tt = 0;
当我们排序之后我们收到删除第一个元素的操作之后,我们可以直接从优先队列中删除,因为加元素的时候是首先加到普通队列中,并不会影响优先队列,然后重复上述操作,即可完成。
AC code:
#include <set>
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 2e5 + 10;
int q;
int a[N];
priority_queue <int ,vector <int>,greater <int> > heap;
int main()
{
scanf("%d",&q);
int tt = 0,hh = 0;
while(q--)
{
int cmd,k;
scanf("%d",&cmd);
if(cmd == 1)
{
scanf("%d",&k);
a[tt ++] = k;
}
if(cmd == 2)
{
if(!heap.size())
printf("%d\n",a[hh ++]);
else
{
int a = heap.top();
heap.pop();
printf("%d\n",a);
}
}
if(cmd == 3)
{
for(int i = hh;i < tt;i ++)
{
heap.push(a[i]);
}
hh = 0;
tt = 0;
//如果不清空队列的话,就会加入重复元素
}
}
return 0;
}