用 Treap 实现的单 log LCT
to do : 将 '不会 Splay' 字面上替换成 '我更喜欢 Treap'
不知道是不愿意学,还是菜的学不会,反正我不会 Splay。那么 LCT 怎么办呢?无所谓,Treap 会出手,因为显然 Treap 是存在做到单 log 的做法的,如 https://www.zhihu.com/question/265974013 中所证明到的,也参考了猫在六年前写的 https://immortalco.blog.uoj.ac/blog/2342。
显然 Treap 没法做到像 Splay 那样有一个比较优美的结构(直接把某个点提成 Auxiliary Tree 的根)。实际上动态树本质上就是维护着一棵动态的全局平衡二叉树,所以我们也可以动用 Treap 的一些本质来维护全局的一个平衡。
为了维持类似这样的平衡,如果我们给节点
当然有更简单的办法来达到相似的目的。记录
但是光这么做不行,因为我们需要利用到
然后考虑操作中的一些小细节。Access 操作中,首先把 Treap 按
很显然的,因为各种原因,代码比 Splay LCT 要复杂,常数也更大……当然也有我写的太烂的原因吧。
在模板题中表现劣于大多数的 Splay。有一个原因是因为这个是纯数组,如果用结构题的话可能能得到不少的提升。
测试了一下复杂度。
还有一点就是尽管 3-way 的做法可以保证复杂度,但是实际上提升了代码复杂度和常数。还没有测试过换成更加简便的写法后会有什么变化,可能会更快吧(
namespace LCT {
int ls[N],rs[N],wt[N],sz[N],fa[N],tag[N],st[N],s[N],top;
struct trp {int l,r,f; trp(int _l=0,int _r=0,int _f=0) {l=_l,r=_r,f=_f;};};
int rand(int x) {return rnd()%x;}
void debug() {cout<<"LCT: \n";rep(i,1,n) printf("%d %d %d %d %d\n",i,ls[i],rs[i],fa[i],sz[i]);}
void init() {rep(i,1,n) wt[i]=sz[i]=1, s[i]=a[i];}
void rev(int x) {tag[x]^=1, swap(ls[x],rs[x]);}
void pd(int x) {if(tag[x]) rev(ls[x]),rev(rs[x]),tag[x]=0;}
void pu(int x) {sz[x]=sz[ls[x]]+sz[rs[x]]+wt[x], s[x]=s[ls[x]]^s[rs[x]]^a[x];}
void uw(int x,int y) {sz[x]=(wt[x]+=y);}
int gettop(int x) {while(fa[x]>0) x=fa[x]; return x;}
int merge(int x,int y) {
if(!x||!y) return x+y; bool op=(rand(sz[x]+sz[y])<sz[x]);
if(op) return pd(x), fa[rs[x]=merge(rs[x],y)]=x, pu(x), x;
else return pd(y), fa[ls[y]=merge(x,ls[y])]=y, pu(y), y;
}
int merge(int x,int u,int y) {
if(!x&&!y) return u; int wd=rand(sz[x]+sz[y]+wt[u]);
if(wd<sz[x]) return pd(x), fa[rs[x]=merge(rs[x],u,y)]=x, pu(x), x;
else if(wd<sz[x]+wt[u]) return ls[u]=x, rs[u]=y, fa[x]=fa[y]=u, pu(u), u;
else return pd(y), fa[ls[y]=merge(x,u,ls[y])]=y, pu(y), y;
}
trp split(int x) {
top=0; do {st[++top]=x, x=fa[x];} while(x>0); x=st[1];
per(i,top,1) pd(st[i]); int l=ls[x], r=rs[x], f=fa[st[top]];
rep(i,2,top)
if(st[i-1]==ls[st[i]]) ls[st[i]]=r, fa[r]=st[i], pu(r=st[i]);
else rs[st[i]]=l, fa[l]=st[i], pu(l=st[i]);
return fa[l]=fa[r]=ls[x]=rs[x]=fa[x]=0, s[x]=a[x], trp(l,r,f);
}
void rew(int x,int y) {
trp tmp=split(x); uw(x,y);
x=merge(tmp.l,x,tmp.r); fa[x]=tmp.f;
}
int acs(int x) {
trp tmp=split(-fa[x]); fa[tmp.r]=fa[x], uw(-fa[x],sz[tmp.r]-sz[x]);
return x=merge(tmp.l,-fa[x],x), fa[x]=tmp.f, x;
}
void access(int x) {
trp tmp=split(x); fa[tmp.r]=-x, uw(x,sz[tmp.r]);
x=merge(tmp.l,x), fa[x]=tmp.f; while(fa[x]) x=acs(x);
}
void makeroot(int x) {access(x); rev(gettop(x));}
void link(int x,int y) {
makeroot(y), access(x), y=gettop(y);
if(y!=gettop(x)) fa[y]=-x, rew(x,sz[y]);
}
void cut(int x,int y) {
makeroot(y), access(x);
if(wt[x]+wt[y]==sz[gettop(x)]&&gettop(x)==gettop(y)) split(x), sz[x]=wt[x], s[x]=a[x];
}
void mdf(int x,int z) {while(x>0) s[x]^=z, x=fa[x];}
int qry(int x,int y) {return makeroot(y), access(x), s[gettop(x)];}
}