普通平衡树
在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