[學習筆記] 替罪羊樹
阿新 • • 發佈:2019-02-05
好像不重構的替罪羊樹跑得最快……
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<climits>
#include<assert.h>
#define N 100010
#define alpha 0.78
#define debug(x) cerr<<#x<<"="<<x
#define sp <<" "
#define ln <<endl
using namespace std;
inline int inn()
{
int x;scanf("%d",&x);return x;
}
int lc[N],rc[N],cnt[N],sz[N],rsz[N],fa[N];
int lst[N],rt,val[N],node_cnt,lst_top;
inline int new_node(int v)
{
int x=++node_cnt;val[x]=v;
return cnt[x]=sz[x]=rsz[x]=1,x;
}
inline int gw(int x) { return rc[fa[x]]==x; }
inline int push_up(int x)
{
return rsz[x]=rsz[lc[x]]+rsz[rc[x]]+1,
sz[x]=sz[lc[x]]+sz[rc[x]]+cnt[x];
}
inline int setc(int x,int y,int z)
{
if(!x) return fa[rt=y]=0;
if(z) rc[x]=y;else lc[x]=y;
if(y) fa[y]=x;return push_up(x);
}
int get_list(int x)
{
if(lc[x]) get_list(lc[x]);
lst[++lst_top]=x;
if (rc[x]) get_list(rc[x]);
return 0;
}
int rebuild(int a,int b)
{
if(a>b) return 0;int c=(a+b)>>1;
int x=rebuild(a,c-1),y=rebuild(c+1,b);
return setc(lst[c],x,0),setc(lst[c],y,1),lst[c];
}
inline int balance(int x)
{
//return 0;
int f=fa[x],w=gw(x);lst_top=0;
get_list(x),x=rebuild(1,lst_top);
setc(f,x,w);return x;
}
inline int ins(int v)
{
int x=rt,las=0,y=0;
while(x)
{
las=x;
if(v<val[x]) x=lc[x];
else if(val[x]<v) x=rc[x];
else break;
}
if(x) cnt[x]++,sz[x]++;
else x=new_node(v),setc(las,x,v>val[las]);
while(x)
{
push_up(x);
if(max(lc[x][rsz],rc[x][rsz])>alpha*rsz[x]) y=x;
x=fa[x];
}
if(y) balance(y);return 0;
}
inline int del(int v)
{
int x=rt;
while(x)
{
if(v<val[x]) x=lc[x];
else if(v==val[x]) break;
else x=rc[x];
}
if(!x) return 0;cnt[x]--,sz[x]--;
if(!cnt[x])
{
if(!lc[x]) setc(fa[x],rc[x],gw(x)),x=fa[x];
else if(!lc[x][rc]) setc(lc[x],rc[x],1),setc(fa[x],lc[x],gw(x)),x=lc[x];
else{
int y=lc[x],z;while(rc[y]) y=rc[y];z=fa[y];
setc(z,lc[y],1),setc(y,lc[x],0),setc(y,rc[x],1);
setc(fa[x],y,gw(x)),x=z;
}
}
while(x) push_up(x),x=fa[x];
return 0;
}
inline int rk(int v)
{
int ans=0,x=rt;
while(x)
{
if(v<val[x]) x=lc[x];
else if(v==val[x]) return ans+lc[x][sz]+1;
else ans+=lc[x][sz]+cnt[x],x=rc[x];
}
return ans;
}
inline int kth(int k)
{
int x=rt;
while(x)
{
if(k<=lc[x][sz]) { x=lc[x];continue; }
k-=lc[x][sz];if(k<=cnt[x]) return val[x];
k-=cnt[x],x=rc[x];
}
return 0;
}
inline int pre(int v)
{
int x=rt,ans=INT_MIN;
while(x)
{
if(val[x]<v) ans=max(ans,val[x]),x=rc[x];
else x=lc[x];
}
return ans;
}
inline int post(int v)
{
int x=rt,ans=INT_MAX;
while(x)
{
if(val[x]>v) ans=min(ans,val[x]),x=lc[x];
else x=rc[x];
}
return ans;
}
int main()
{
rt=1,node_cnt=2,
val[1]=INT_MIN,val[2]=INT_MAX,
rsz[1]=rsz[2]=1,rc[1]=2,fa[2]=1;
//show(rt);cerr ln;
for(int q=inn();q;q--)
{
switch(inn())
{
case 1:ins(inn());break;
case 2:del(inn());break;
case 3:printf("%d\n",rk(inn()));break;
case 4:printf("%d\n",kth(inn()));break;
case 5:printf("%d\n",pre(inn()));break;
case 6:printf("%d\n",post(inn()));break;
}
//show(rt);cerr ln;
}
return 0;
}