目前已知的问题好像是各节点没有连起来,每个节点的左右孩子只有 0 或 1 ,其他代码目测没有什么问题(当然也可能是我太菜了)
#include<bits/stdc++.h>
using namespace std;
typedef double db;
typedef long long ll;
typedef unsigned long long ull;
struct tree{
int val,sonsize,cnt,l,r,rd;
}t[15000];
int sum;
void update(int p){
t[p].sonsize=t[t[p].l].sonsize+t[t[p].r].sonsize+t[p].cnt;
}
void lrotate(int &p){
int temp=t[p].r;
t[p].r=t[temp].l;
t[temp].l=p;
update(p),update(temp);
p=temp;
}
void rrotate(int &p){
int temp=t[p].l;
t[p].l=t[temp].r;
t[temp].r=p;
update(p),update(temp);
p=temp;
}
void add(int &p,int k){
if(p==0){
t[++sum].val=k;
t[sum].cnt=1;
t[sum].sonsize=1;
t[sum].rd=rand();
p=sum;
return;
}
if(k==t[p].val){
t[p].cnt++;
t[p].sonsize++;
return ;
}
if(k<t[p].val){
add(t[p].l,k);
if(t[p].rd<t[t[p].l].rd) rrotate(p);
}
if(k>t[p].val){
add(t[p].r,k);
if(t[p].rd<t[t[p].r].rd) lrotate(p);
}
update(p);
}
int rank_val(int p,int k){
if(p==0) return INT_MAX;
if(t[t[p].l].sonsize>=k) return rank_val(t[p].l,k);
if(t[t[p].l].sonsize+t[p].cnt>=k) return t[p].val;
return rank_val(t[p].r,k-t[t[p].l].sonsize-t[p].cnt);
}
int val_rank(int p,int v){
if(p==0) return 0;
if(v==t[p].val) return t[t[p].l].sonsize+1;
if(v<t[p].val) return val_rank(t[p].l,v);
return val_rank(t[p].r,v)+t[t[p].l].sonsize+t[p].cnt;
}
int xlast(int p,int x){
int ans=INT_MIN;
while(p){
cout<<p<<" ";
if(x==t[p].val){
if(t[p].l){
p=t[p].l;
while(t[p].r){
p=t[p].r;
}
return t[p].val;
}else{
return ans;
}
}
if(t[p].val<x&&t[p].val>ans) ans=t[p].val;
p=x<t[p].val?t[p].l:t[p].r;
}
return ans;
}
int xnext(int p,int x){
int ans=INT_MAX;
while(p){
if(x==t[p].val){
if(t[p].r){
p=t[p].r;
while(t[p].l){
p=t[p].l;
}
return t[p].val;
}else{
return ans;
}
}
if(t[p].val>x&&t[p].val<ans) ans=t[p].val;
p=x<t[p].val?t[p].l:t[p].r;
}
return ans;
}
void del(int &p,int k){
if(p==0) return;
if(k<t[p].val) del(t[p].l,k);
else if(k>t[p].val) del(t[p].r,k);
else{
if(t[t[p].l].val==0&&t[t[p].r].val==0){
t[p].cnt--;
t[p].sonsize--;
if(t[p].cnt==0) p=0;
}
else if(t[t[p].l].val==0){
lrotate(p);
del(t[p].l,k);
}
else if(t[t[p].r].val==0){
rrotate(p);
del(t[p].r,k);
}
else{
if(t[t[p].l].rd>t[t[p].r].rd){
rrotate(p);
del(t[p].r,k);
}
else{
lrotate(p);
del(t[p].l,k);
}
}
}
update(p);
}
int q;
int c,x;
int ttt=0;
int z=1;
int main()
{
ios::sync_with_stdio(false);
cin>>q;
for(int i=1;i<=q;i++){
cin>>c>>x;
if(c==1){
add(ttt,x),ttt=1;
//for(int i=1;i<=sum;i++) cout<<t[i].l<<" "<<t[i].r<<" "<<t[i].rd<<" "<<t[i].val<<"\n";
}
else if(c==2) del(z,x);
else if(c==3) cout<<val_rank(1,x)<<endl;
else if(c==4) cout<<rank_val(1,x)<<endl;
else if(c==5) cout<<xlast(1,x)<<endl;
else cout<<xnext(1,x)<<endl;
}
return 0;
}