rt,record。
第一组数据:
4
1 10
1 30
1 20
3 21
正确答案是 3。
本地 win10 和 linux 虚拟机下结果均为 3,但在测评机和 ide 下结果为 2。
代码如下:
#include<bits/stdc++.h>
using namespace std;
const int M=1000005;
int n,opt,x,rt,tot,val[M];
int cnt[M],siz[M],fa[M],son[M][2];
void update(int x){
siz[x]=cnt[x]+siz[son[x][0]]+siz[son[x][1]];
}
bool isRson(int x){
return (x==son[fa[x]][1]);
}
void rotate(int x){
int y=fa[x],z=fa[y];
bool b0=isRson(x),b1=isRson(y);
if(son[x][b0^1]) fa[son[x][b0^1]]=y;
son[y][b0]=son[x][b0^1];
fa[y]=x;
son[x][b0^1]=y;
fa[x]=z;
if(z) son[z][b1]=x;
update(y);
update(x);
}
void splay(int x){
for(int p;p=fa[x],p;rotate(x))
if(fa[p]) rotate(isRson(x)==isRson(p)?p:x);
rt=x;
}
void ins(int x){
if(!rt){
rt=++tot;
val[tot]=x;
cnt[tot]=siz[tot]=1;
fa[tot]=son[tot][0]=son[tot][1]=0;
return;
}
int now=rt;
while(now){
if(val[now]==x){
++cnt[now];
++siz[now];
splay(now);
return;
}
if(x<val[now]){
if(!son[now][0]){
siz[++tot]=cnt[tot]=1;
son[now][0]=tot;
fa[tot]=now;
son[tot][0]=son[tot][1]=0;
val[tot]=x;
splay(tot);
return;
}
now=son[now][0];
}
else{
if(!son[now][1]){
siz[++tot]=cnt[tot]=1;
son[now][1]=tot;
fa[tot]=now;
son[tot][0]=son[tot][1]=0;
val[tot]=x;
splay(tot);
return;
}
now=son[now][1];
}
}
}
int queryrank(int x){
int res=0,now=rt;
while(now){
if(x<val[now]) now=son[now][0];
else if(x==val[now]){
res+=siz[son[now][0]];
splay(now);
return res+1;
}
else{
res+=siz[son[now][0]]+cnt[now];
now=son[now][1];
}
}
return res+1;
}
int querykth(int x){
int now=rt;
while(now){
if(x<=siz[son[now][0]]) now=son[now][0];
else if(x<=siz[son[now][0]]+cnt[now]){
splay(now);
return val[now];
}
else{
x-=siz[son[now][0]]+cnt[now];
now=son[now][1];
}
}
return 0;
}
void del(int x){
queryrank(x);
if(cnt[rt]>1){
--cnt[rt];
--siz[rt];
return;
}
if(!son[rt][0]&&!son[rt][1]){
siz[rt]=cnt[rt]=0;
rt=0;
return;
}
if(!son[rt][0]&&son[rt][1]){
int rson=son[rt][1];
fa[rson]=0;
siz[rt]=cnt[rt]=son[rt][1]=0;
rt=rson;
return;
}
if(son[rt][0]&&!son[rt][1]){
int lson=son[rt][0];
fa[lson]=0;
siz[rt]=cnt[rt]=son[rt][0]=0;
rt=lson;
return;
}
if(son[rt][0]&&son[rt][1]){
int lson=son[rt][0];
int now=son[rt][1];
fa[lson]=fa[now]=0;
siz[rt]=cnt[rt]=son[rt][0]=son[rt][1]=0;
while(son[now][0]) now=son[now][0];
splay(now);
son[rt][0]=lson;
fa[lson]=rt;
update(rt);
return;
}
}
int querypre(int x){
ins(x);
int now=son[rt][0];
while(son[now][1]) now=son[now][1];
del(x);
return val[now];
}
int querynxt(int x){
ins(x);
int now=son[rt][1];
while(son[now][0]) now=son[now][0];
del(x);
return val[now];
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d%d",&opt,&x);
if(opt==1) ins(x);
if(opt==2) del(x);
if(opt==3) printf("%d\n",queryrank(x));
if(opt==4) printf("%d\n",querykth(x));
if(opt==5) printf("%d\n",querypre(x));
if(opt==6) printf("%d\n",querynxt(x));
}
}
求助大佬调试