Splay
ysy11
·
·
个人记录
namespace Splaytree{
struct node
{
ll fa,s[2],cnt,ky,size,la;
}t[MAXN];
ll num,root;
ll newnode(ll x,ll y)
{
num++;
t[num].cnt=t[num].size=1;
t[num].ky=x;
t[num].fa=y;
return num;
}
void pushup(ll x)
{
ll ls=t[x].s[0],rs=t[x].s[1];
t[x].size=t[ls].size+t[rs].size;
t[x].size+=t[x].cnt;
}
void pushdown(ll x)
{
if(x&&t[x].la)
{
swap(t[x].s[0],t[x].s[1]);
t[t[x].s[0]].la^=1;
t[t[x].s[1]].la^=1;
t[x].la=0;
}
}
ll build(ll l,ll r,ll fa)
{
ll mid=l+r>>1,x=newnode(a[mid],fa);
if(l==r)return x;
if(l<mid)t[x].s[0]=build(l,mid-1,x);
if(r>mid)t[x].s[1]=build(mid+1,r,x);
pushup(x);
return x;
}
bool chk(ll x)
{
pushdown(t[x].fa);
return t[t[x].fa].s[1]==x;
}
void rotate(ll x)
{
ll fa=t[x].fa,ga=t[fa].fa;
pushdown(x);
ll tt=chk(x);
t[ga].s[chk(fa)]=x;
t[x].fa=ga;
t[fa].s[tt]=t[x].s[tt^1];
t[t[x].s[tt^1]].fa=fa;
t[x].s[tt^1]=fa;
t[fa].fa=x;
pushup(fa);
pushup(x);
}
void splay(ll x,ll y)
{
while(t[x].fa!=y)
{
ll fa=t[x].fa,ga=t[fa].fa;
if(ga!=y)
{
rotate(chk(x)^chk(fa)?x:fa);
}
rotate(x);
}
if(y==0)
{
root=x;
}
}
void add(ll x)
{
ll y=root,fa=0;
while(y&&t[y].ky!=x)
{
pushdown(y);
fa=y;
y=t[y].s[t[y].ky<x];
}
if(y)
{
t[y].cnt++;
}
else
{
y=newnode(x,fa);
if(fa)
{
t[fa].s[x>t[fa].ky]=y;
}
}
splay(y,0);
}
void prepare(ll x)
{
ll y=root;
if(!y)return ;
pushdown(y);
while(t[y].s[t[y].ky<x]&&t[y].ky!=x)
{
y=t[y].s[t[y].ky<x];
pushdown(y);
}
splay(y,0);
}
ll get(ll x,bool y)
{
prepare(x);
ll z=root;
if(t[z].ky<x&&!y)return z;
if(t[z].ky>x&&y)return z;
z=t[z].s[y];
pushdown(z);
while(t[z].s[y^1])
{
z=t[z].s[y^1];
pushdown(z);
}
splay(z,0);
return z;
}
void del(ll x)
{
ll y=get(x,0),z=get(x,1);
splay(y,0);
splay(z,y);
pushdown(z);
if(t[t[z].s[0]].cnt>1)
{
t[t[z].s[0]].cnt--;
splay(t[z].s[0],0);
}
else
{
t[z].s[0]=0;
splay(z,0);
}
}
ll rk(ll x)
{
prepare(x);
return t[t[root].s[0]].size;
}
ll kth(ll x)
{
x++;
ll y=root;
if(t[y].size<x)return 0;
while(1)
{
pushdown(y);
ll ls=t[y].s[0];
if(t[ls].size>=x)
{
y=ls;
continue;
}
x-=t[ls].size;
if(t[y].cnt>=x)
{
splay(y,0);
return y;
}
x-=t[y].cnt;
y=t[y].s[1];
}
}
void reverse(ll l,ll r)
{
ll L=kth(l-1),R=kth(r+1);
splay(L,0);
splay(R,L);
t[t[R].s[0]].la^=1;
}
void ask(ll x)
{
pushdown(x);
if(t[x].s[0])ask(t[x].s[0]);
if(abs(t[x].ky)!=inf)cout<<t[x].ky<<" ";
if(t[x].s[1])ask(t[x].s[1]);
}
}using namespace Splaytree;