传送门
今天突发奇想写了个指针Splay,居然还很神奇地调过了
其实就是按着原来的板子写,然后改成指针罢了
注意要用null代替NULL,不然很有可能RE
具体写法可以看我的代码(虽然是自己YY的,可是还是可以看的吧)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#define ll long long
using namespace std;
inline int read(){
int x=0;char ch=' ';int f=1;
while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
if(ch=='-')f=-1,ch=getchar();
while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
return x*f;
}
const int N=1e5+5;
struct node{
node *ch[2],*fa;
int key,cnt,size;
node(){key=cnt=size=0;}
inline bool get(){return fa->ch[1]==this;}
inline void update(){size=ch[0]->size+ch[1]->size+cnt;}
inline void clear(){key=cnt=size=0;}
}t[N],*null,*root;
int n,sz;
inline node* New(){++sz;t[sz].ch[0]=t[sz].ch[1]=t[sz].fa=null;return &t[sz];}
inline void rotate(node *x){
node *y=x->fa,*z=y->fa;int w=x->get(),w2=y->get();
y->ch[w]=x->ch[w^1]; y->ch[w]->fa=y;
x->ch[w^1]=y; y->fa=x;
x->fa=z; if(z!=null)z->ch[w2]=x;
y->update(); x->update();
}
inline void Splay(node *x){
for(node *fa=null;(fa=x->fa)!=null;rotate(x))
if(fa->fa!=null)
rotate((fa->get()==x->get())?fa:x);
root=x;
}
inline void insert(int x){
if(root==null){root=New();root->key=x;root->cnt=root->size=1;return;}
node *now=root,*fa=null;
while(1){
if(x==now->key){now->cnt++;Splay(now);return;}
fa=now;
now=now->ch[x>now->key];
if(now==null){
fa->ch[x>fa->key]=now=New();
now->key=x;now->cnt=1;now->fa=fa;
Splay(now);return;
}
}
}
inline int kth(int k){
node *now=root;
while(1){
if(now->ch[0]!=null&&k<=now->ch[0]->size)now=now->ch[0];
else{
int lsize=now->ch[0]->size+now->cnt;
if(k<=lsize)return now->key;
k-=lsize;now=now->ch[1];
}
}
}
inline int Rank(int x){
node *now=root;int ans=0;
while(1){
if(now->ch[0]!=null&&x<now->key)now=now->ch[0];
else{
ans+=now->ch[0]->size;
if(x==now->key){Splay(now);return ans;}
ans+=now->cnt;now=now->ch[1];
}
}
}
inline node* pre(){
node *now=root->ch[0];
while(now->ch[1]!=null)now=now->ch[1];
return now;
}
inline void del(int x){
Rank(x);
if(root->cnt>1){root->cnt--;root->update();return;}
node *left=pre(),*oldroot=root;
Splay(left);
left->ch[1]=oldroot->ch[1];
left->ch[1]->fa=left;
oldroot->clear();
root->update();
}
const int inf=0x3f3f3f3f;
inline int Pre(node *now,int val){
if(now==null)return -inf;
if(val>now->key)return max(now->key,Pre(now->ch[1],val));
else return Pre(now->ch[0],val);
}
inline int Next(node *now,int val){
if(now==null)return inf;
if(val<now->key)return min(now->key,Next(now->ch[0],val));
else return Next(now->ch[1],val);
}
int main(){
root=null=&t[0];
n=read();insert(inf);insert(-inf);
while(n--){
int opt=read(),x=read();
switch(opt){
case 1:insert(x);break;
case 2:del(x);break;
case 3:printf("%d\n",Rank(x));break;
case 4:printf("%d\n",kth(x+1));break;
case 5:printf("%d\n",Pre(root,x));break;
case 6:printf("%d\n",Next(root,x));break;
}
}
return 0;
}