发现错误的是qval(4.查询数据结构中排名为 x 的数。)的时候没有搜到,返回了0,不知道是为什么。
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+15,INF=1e9;
int n,idx,op,x,rt,cnt;
struct node{
int lc,rc,key,pri,cnt,sze;
#define lc(x) tr[x].lc
#define rc(x) tr[x].rc
#define v(x) tr[x].key
#define p(x) tr[x].pri
#define c(x) tr[x].cnt
#define s(x) tr[x].sze
}tr[N];
inline void upt(const int &id){
s(id)=s(lc(id))+s(rc(id))+c(id);
}
inline void Zig(int &id){
int y=lc(id);
lc(id)=rc(y);
rc(y)=id;
s(id)=s(id);
upt(id);
id=y;
}
inline void Zag(int &id){
int y=rc(id);
rc(id)=lc(y);
lc(y)=id;
s(y)=s(id);
upt(id);
id=y;
}
inline void Ins(int &id,const int &key){
if(!id){
id=++idx;
v(id)=key;
p(id)=rand();
c(id)=s(id)=1;
lc(id)=rc(id)=0;
return ;
}
else{
++s(id);
}
if(v(id)==key){
++c(id);
}
else if(key<v(id)){
Ins(lc(id),key);
if(p(lc(id))<p(id)){
Zig(id);
}
}
else{
Ins(rc(id),key);
if(p(rc(id))<p(id)){
Zag(id);
}
}
return ;
}
inline void Del(int &id,const int &key){
if(v(id)==key){
if(c(id)>1){
--c(id),--s(id);
}
else if(!lc(id)||!rc(id)){
id=lc(id)+rc(id);
}
else if(p(lc(id))<p(rc(id))){
Zig(id);
Del(id,key);
}
else{
Zag(id);
Del(id,key);
}
return ;
}
--s(id);
if(key<v(id)){
Del(lc(id),key);
}
else{
Del(rc(id),key);
}
return ;
}
inline int qpre(const int &key){
int id=rt,ret=-INF;
while(id){
if(v(id)<key){
ret=v(id),id=rc(id);
}
else{
id=lc(id);
}
}
return ret;
}
inline int qnxt(const int &key){
int id=rt,ret=INF;
while(id){
if(v(id)>key){
ret=v(id),id=lc(id);
}
else{
id=rc(id);
}
}
return ret;
}
inline int qval(int k){
int id=rt;
while(id){
if(s(lc(id))<k&&s(lc(id))+c(id)>=k){
return v(id);
}
if(s(lc(id))>=k){
id=lc(id);
}
else{
k-=s(lc(id))+c(id);
id=rc(id);
}
}
return 0;
}
inline int qrnk(const int &key){
int id=rt,ret=0;
while(id){
if(key==v(id)){
ret+=s(lc(id))+1;
return ret;
}
else if(key<v(id)){
id=lc(id);
}
else{
ret+=s(lc(id))+c(id),id=rc(id);
}
}
return ret+1;
}
inline int read(){
int w=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-') f=-1;
ch=getchar();
}
while('0'<=ch&&ch<='9'){
w=w*10+ch-'0';
ch=getchar();
}
return w*f;
}
inline void write(int x){
if(x<0) putchar('-'),x=-x;
if(x>9) write(x/10);
putchar(x%10+'0');
}
int main(){
//srand(time(NULL));
//n=read();
cin>>n;
for(int i = 1 ; i<=n ; i++){
//op=read(),x=read();
cin>>op>>x;
if(op==1){
if(cnt==0){
++idx,rt=idx;
tr[idx]={0,0,x,rand(),1,1};
}
else{
Ins(rt,x);
}
cnt=1;
}
else if(op==2){
Del(rt,x);
//--cnt;
}
else if(op==3){
// write(qrnk(x));
// putchar('\n');
cout<<qrnk(x)<<endl;
}
else if(op==4){
// write(qval(x));
// putchar('\n');
cout<<qval(x)<<endl;
}
else if(op==5){
// write(qpre(x));
// putchar('\n');
cout<<qpre(x)<<endl;
}
else if(op==6){
// write(qnxt(x));
// putchar('\n');
cout<<qnxt(x)<<endl;
}
}
return 0;
}
/*5
1 1
1 3
1 2
2 3
4 2*/