低配版平衡树

普通平衡树

在acwing和洛谷上都有它的模板题:
acwing 253
洛谷 3369

对C++内置的红黑树进行二次封装,可以作为基础平衡树的替代品,用来辅助其他算法,理论复杂度nlogn,常数比手写平衡树略大。

#pragma GCC optimize(3,"Ofast","inline")

#include<bits/stdc++.h>
#include<bits/extc++.h>

using namespace std;
using namespace __gnu_pbds;

#define BEGIN signed main(){ios::sync_with_stdio(0),cin.tie(0);
#define END return 0;}

typedef pair<int,int> pii;
typedef tree<pii,null_type,less<pii>,rb_tree_tag,tree_order_statistics_node_update> rbt;

struct BST
{
    rbt bst;
    rbt::iterator it;
    int bst_inf=0x7fffffff,id=0;
    
    int size(){return bst.size();}
    void clear(){bst.clear();}
    bool exist(int x)
    {
        it=bst.lower_bound({x,0});
        return it!=bst.end()&&it->first==x;
    }
    
    void insert(int x){bst.insert({x,++id});}
    void erase(int x)
    {
        if(!exist(x))return;
        bst.erase(it);
    }

    int order_of_key(int x){return bst.order_of_key({x,0})+1;}
    int find_by_rank(int x)
    {
        if(x>size())return bst_inf;
        return bst.find_by_order(x-1)->first;
    }

    int pre(int x)
    {
        it=bst.lower_bound({x,0});
        if(it==bst.begin())return bst_inf;
        return (--it)->first;
    }
    int nxt(int x)
    {
        it=bst.lower_bound({x+1,0});
        if(it==bst.end())return bst_inf;
        return it->first;
    }
};

BEGIN
#ifdef FSLSE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
#endif 
    
    BST t;
    int n;
    cin>>n;
    while(n--)
    {
        int op,x;
        cin>>op>>x;
        switch(op)
        {
            case 1:t.insert(x);break;
            case 2:t.erase(x);break;
            case 3:cout<<t.order_of_key(x)<<'\n';break;
            case 4:cout<<t.find_by_rank(x)<<'\n';break;
            case 5:cout<<t.pre(x)<<'\n';break;
            case 6:cout<<t.nxt(x)<<'\n';break;
        }
    }

END

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值