可允许重复数字的平衡树
注意:速度比普通的手写的平衡树慢3倍,以及因为是维护的元素是结构体,使用lower_bound和upper_bound速度非常慢,要使用order_of_key(int x)来代替upper_bound来使用,其功能是查询比x小的数有多少个
#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;
int N,op,x;
struct Tree{
int inf = 1e9,idx = 0;
struct node{
int x,tim;
bool operator <(node o) const{
if(x != o.x) return x < o.x;
else return tim < o.tim;
}
};
tree<node, null_type, less<node>, rb_tree_tag, tree_order_statistics_node_update> T;
void insert(int x){
T.insert({x,++idx});
}
bool have(int x){ //判断是否有x
node cur = {x,0};
int order = T.order_of_key(cur);
if(order + 1 > (int)T.size()) return 0;
auto it = T.find_by_order(order);
if((*it).x != x) return 0;
return 1;
}
void erase(int x){
if(!have(x)) return ;
node cur = {x,0};
int order = T.order_of_key(cur);
auto it = T.find_by_order(order);
T.erase(it);
}
int getrank(int x){ //查询x的排名
return T.order_of_key({x,0}) + 1;
}
int getbyrank(int rank){ //通过排名x的元素是谁
if((int)T.size() < rank) return -inf;
return (*T.find_by_order(rank-1)).x;
}
int getpre(int x){//查询比x小,且最大的数
int rank = getrank(x);
if(rank == 1) return -inf;
return getbyrank(rank-1);
}
int getnex(int x){//查询比x大,且最小的数
int rank = getrank(x+1);
if(rank > (int)T.size()) return -inf;
return getbyrank(rank);
}
}tr;
int main()
{
cin>>N;
for(int i = 1;i<=N;i++){
int op,x;scanf("%d %d",&op,&x);
if(op == 1) tr.insert(x);
if(op == 2) tr.erase(x);
if(op == 3) printf("%d\n",tr.getrank(x));
if(op == 4) printf("%d\n",tr.getbyrank(x));
if(op == 5) printf("%d\n",tr.getpre(x));
if(op == 6) printf("%d\n",tr.getnex(x));
}
return 0;
}
可重复数字平衡树版本2
如果题目保证每一步都是合法的,可以用此版本,更少的代码量
#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;
int N,op,x;
struct Tree{
int idx = 0;
struct node{
int x,tim;
bool operator <(node o) const{
if(x != o.x) return x < o.x;
else return tim < o.tim;
}
};
tree<node, null_type, less<node>, rb_tree_tag, tree_order_statistics_node_update> T;
void insert(int x){
T.insert({x,++idx});
}
void erase(int x){
int rank = T.order_of_key({x,0});
auto it = T.find_by_order(rank);
T.erase(it);
}
int getrank(int x){
return T.order_of_key({x,0}) + 1;
}
int getbyrank(int x){
return (*T.find_by_order(x-1)).x;
}
int getpre(int x){
int rank = T.order_of_key({x,0});
return (*T.find_by_order(rank-1)).x;
}
int getnex(int x){
int rank = T.order_of_key({x+1,0});
return (*T.find_by_order(rank)).x;
}
}tr;
int main()
{
// freopen("in.txt","r",stdin);
cin>>N;
for(int i = 1;i<=N;i++){
scanf("%d %d",&op,&x);
if(op == 1) tr.insert(x);
if(op == 2) tr.erase(x);
if(op == 3) printf("%d\n",tr.getrank(x));
if(op == 4) printf("%d\n",tr.getbyrank(x));
if(op == 5) printf("%d\n",tr.getpre(x));
if(op == 6) printf("%d\n",tr.getnex(x));
}
return 0;
}
无重复数字版本
可以直接使用
tree<node, null_type, less<node>, rb_tree_tag, tree_order_statistics_node_update> T;
写有重复数字版本,完全是因为这个库的tree不能有重复数字,所以才自己去封装可重复版本。