P1486 [NOI2004] 郁闷的出纳员

· · 题解

P1486 [NOI2004] 郁闷的出纳员

题意简述

要求维护一个可重集合,支持以下操作:

  1. 添加一个值为 k 的元素
  2. 将集合中的每个元素增加 k
  3. 将集合中的每个元素减少 k
  4. 查询集合中第 k 大元素的值

每次操作后需要删除小于 m 的元素,最后求删除的元素数量。

思路简述

作者在 神秘网站 搜索平衡树,立刻得到了 这个词条。写完 Splay 调不出来,遂用 pb_ds 切了这题。

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;

使用 pb_ds 需要引用以上命名空间。

tree<ll,null_type,greater<ll>,rb_tree_tag,tree_order_statistics_node_update> btree,tmp;

以上代码为平衡树的建立。下面介绍几个参数的意义。

  1. 表示平衡树的数据类型,如果需要一个节点需存储多个数据,可以改为结构体或 pair 嵌套。
  2. 这个参数可以将平衡树的存储方式设为 不可重集,可以改为 map<key,val> 的形式以采用映射的存储方式。
  3. 元素之间的比较方式。填入仿函数。
  4. 数据结构。一般不改动,红黑树效率最高。
  5. 不填(默认 null_node_update)则无法使用 order_of_key 和 find_by_order 成员函数。
  6. 一般不填。

先介绍几个本题会用到的 pb_ds 成员函数。

其它成员函数可以看 oi-wiki。

有了 pb_ds,本题就非常简单了。下面逐一分析每个操作。由于本题是可重集合,而如果直接存的话遇到相同元素会被吃掉。所以需要用 pair 增加一维。不妨存操作编号。

时间复杂度 O(n\log k),空间复杂度 O(n)。

代码实现

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
typedef long long ll;
ll n,m,ans,k,now;
char op;
tree<pair<ll,ll>,null_type,greater<pair<ll,ll> >,rb_tree_tag,tree_order_statistics_node_update> btree,tmp;
ll read(){
    ll x = 0;
    bool f = true;
    char ch = getchar();
    while(!isdigit(ch)){
        if(ch == '-')f = !f;
        ch = getchar();
    }
    while(isdigit(ch))x = x * 10 + ch - '0',ch = getchar();
    return x * f * 2 - x;
}
ll write(ll x,string ch){
    ll f = 1,L = ch.size(),tmp = x;
    if(tmp < 0){
        putchar('-');
        tmp *= -1;
    }
    while(f <= tmp)f *= 10;
    if(tmp)f /= 10;
    while(f){
        putchar(tmp / f + '0');
        tmp -= (tmp / f * f),f /= 10;
    }
    for(ll i = 0;i <= L - 1;i++)putchar(ch[i]);
    return x;
}
int main(){
    n = read(),m = read();
    for(ll i = 1;i <= n;i++){
        scanf(" %c",&op);
        k = read();
        if(op == 'I' && k >= m)btree.insert(make_pair(k - now,i));
        else if(op == 'A')now += k;
        else if(op == 'S'){
            now -= k;
            btree.split(make_pair(m - now - 1,n),tmp);
            ans += tmp.size();
        }else if(op == 'F'){
            if(k > btree.size())printf("-1\n");
            else write(btree.find_by_order(k - 1)->first + now,"\n");
        }
    }
    write(ans,"");
    return 0;
}