splay模板
1.updata
void updata(int x) { count2[x]=count2[leftson[x]]+count2[rightson[x]]+1;(加上自己信息) }
2.rotate
void rotate(int x,int y) { int father=fa[x]; if (y==1) { rightson[father]=leftson[x]; if (leftson[x]) fa[leftson[x]]=father; } else { leftson[father]=rightson[x]; if (rightson[x]) fa[rightson[x]]=father; } fa[x]=fa[father]; if (fa[father]) { if (leftson[fa[father]]==father) leftson[fa[father]]=x; else rightson[fa[father]]=x; }
fa[father]=x; if (y==1) leftson[x]=father;else rightson[x]=father; updata(father); updata(x); }
3.splay
void splay(int x,int goal) { if (x==root) return; int father=fa[x]; while (father!=goal) { if (fa[father]==goal) { if (x==leftson[father]) rotate(x,2); else rotate(x,1); } else { if (father==leftson[fa[father]]) { if (x==leftson[father]) rotate(father,2),rotate(x,2); else rotate(x,1),rotate(x,2); } else { if (x==rightson[father]) rotate(father,1),rotate(x,1); else rotate(x,2),rotate(x,1); } }
father=fa[x]; } if (goal==0) root=x; }
4.search
int search(int goal) { int x=root,cnt=1; while (x) { if (cnt+count2[leftson[x]]==goal) return(x); if (count2[leftson[x]]+cnt<goal) { cnt+=count2[leftson[x]]+1; x=rightson[x]; } else { x=leftson[x]; } } }
5.build
#define mid (h+t)/2 void build(int h,int t,int father,bool x,int a[maxn]) { count2[++num]=1; data[num]=a[mid]; fa[num]=father;if (father) { if (x==1) leftson[father]=num; else rightson[father]=num; } int tmp=num; if (h<mid) build(h,mid-1,tmp,1,a); if (mid<t) build(mid+1,t,tmp,0,a); updata(tmp); }
root=(1+n)/2;
6.insert
void insert2(int x) { int y=root; while (y) { count2[y]++; if (x<data[y]) { if (!leftson[y]) break; y=leftson[y]; } else { if (!rightson[y]) break; y=rightson[y]; } } data[++num]=x; fa[num]=y; count2[num]=1; if (x>=data[y]) rightson[y]=num; //注意这个等号 由于上面是小于 所以一定要有 else leftson[y]=num; splay(num,0); }
7.pre
int y=root,maxn=-INF; while (y) { if (data[y]<=x) maxn=max(maxn,data[y]); if (data[y]<=x) y=rightson[y]; else y=leftson[y]; }
8. print
void print(int x) { down(x); if (leftson[x]!=0) print(leftson[x]); if(data[x]>=1&&data[x]<=n) cout<<data[x]<<" "; if (rightson[x]!=0) print(rightson[x]); }
9.delete2
void delete1() { int x=leftson[root]; if (x==0) { root=rightson[root]; fa[root]=0; return; } while (rightson[x]) x=rightson[x]; splay(x,root); rightson[x]=rightson[root]; if (rightson[root]) fa[rightson[root]]=x; updata(x); root=x; fa[x]=0; }
10.query