题解:AT_abc451_c [ABC451C] Understory

· · 题解

题目中需要我们维护两种操作:放入一个新数以及删除所有数中最小的一些数。因此可以用堆来实现,这里我用了 STL 中的优先队列。(不会堆的可以去做一下【模板】堆,与这道题有点像)

具体地,在每个 1 操作直接将 h 放入堆中,在每个 2 操作不断删除堆顶元素直到堆顶元素超过 h 为止,操作结束之后输出堆的大小。

代码:

#include<bits/stdc++.h>
using namespace std;
int Q,op,h;
priority_queue<int,vector<int>,greater<int> >q;//小根堆
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin>>Q;
    while(Q--){
        cin>>op>>h;
        if(op==1){
            q.push(h); //放入堆中
        }
        if(op==2){
            if(q.size()){
                while(q.top()<=h){//在堆顶元素不超过h时一直删除堆顶
                    q.pop();
                    if(q.empty())break;//如果删空了就不能再删了
                }
            }
        }
        cout<<q.size()<<'\n';//输出堆的大小
    }
    return 0;
}