AT_abc217_e Sorting Queries 题解

· · 题解

这道题我们只需要创建一个优先队列和一个普通队列即可。

对于 1 操作,只需要将 x 放入普通队列中即可。

对于 3 操作,只需要将普通队列中的所有数都放入优先队列中即可,优先队列可以自动排序。

而对于 2 操作,若优先队列不为空,则输出优先队列开头的元素,反之则输出普通队列开头的元素。因为如果优先队列不为空,则必然执行过 3 操作,此时原题中的队列开头的元素必为优先队列开头的元素,而普通队列中的元素都被插入在优先队列元素的后面了。

具体见代码

#include<bits/stdc++.h>
using namespace std;
int Q,x,opt;
priority_queue<int,vector<int>,greator<int> > qu;//越小越优先的优先队列
queue<int> q;//普通队列
int main(){
    cin>>Q;
    while(Q--){
        cin>>opt;
        if(opt==1){//1操作
            cin>>x;
            q.push(x);
        }
        else if(opt==2){//2操作
            if(qu.size()){
                cout<<qu.top()<<endl;
                qu.pop();
            }
            else{
                cout<<q.front()<<endl;
                q.pop();
            }
        }
        else{//3操作
            while(q.size()){
                qu.push(q.front());//将普通队列中的数转移到优先队列中
                q.pop();
            }
        }
    }
    return 0;
}