[ABC212D] Querying Multiset

· · 题解

思路:

感觉 priority_queue 好慢啊~

发现这是一个对于堆的模板题目。

对于操作 1,就可以直接使用 STL 库里面的 push_heap 函数,插入这个数之后可以保持堆的性质,对于操作 3,我们可以直接输出 a_1,然后将 a_1 和 a_n 交换一下,使用 pop_heap 函数维护堆。

对于操作 2,如果我们暴力去改肯定要超时,不难发现,我们可以直接存储所有 x 的和 sum,对于后面加入集合的元素,我们需要将其减去 sum,操作 3 的时候,输出 a_1+k,这样我们减去的又加回来了,元素值还是不变的。

对于此题我们要维护的是小根堆,用数组怎么办呢?没事,将其转换为负数就行了。

完整代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1000100;
inline ll read(){
    ll x=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-')
          f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        x=(x<<1)+(x<<3)+(c^48);
        c=getchar();
    }
    return x*f;
}
inline void write(ll x){
    if(x<0){
        putchar('-');
        x=-x;
    }
    if(x>9)
      write(x/10);
    putchar(x%10+'0');
}
ll a[N],q,op,x,sum=0,l=1;
int main(){
    q=read();
    while(q--){
        op=read();
        if(op==1){
            x=read()-sum;
            a[l++]=-x;
            push_heap(a+1,a+l);
        }
        else if(op==2)
          sum+=read();
        else{
            write(-(a[1])+sum),putchar('\n');
            swap(a[1],a[l]);
            pop_heap(a+1,a+l);
            l--;
        }
    }
    return 0;
}