万分感谢Clove_unique学长给我的启发
f[i]表示i的父节点,ch[i][0]表示i的左儿子,ch[i][1]表示i的右儿子,key[i]表示i节点所代表的值,cnt[i]表示key[i]出现的次数(我们将所有值相同的点缩为一个点),size[i]表示i及其子树的大小,sz为整棵树的大小,root为根节点标号
平衡树中的每个节点的左儿子都小于它本身,右儿子都大于它本身(想想二叉搜索树)
没错!其实平衡树的本质其实是二叉搜索树
get:判断当前点是它父结点的左儿子还是右儿子,左儿子返回0,右儿子返回1
bool get(int x) {return ch[f[x]][1]==x;}
update:更新当前节点信息
void update(int x) {
if(x) {
size[x]=cnt[x];
if(ch[x][0]) size[x]+=size[ch[x][0]];
if(ch[x][1]) size[x]+=size[ch[x][1]];
}
return ;
}
pushdown:下传旋转信息
void pushdown(int x) {
if(x && lazy[x]) {
tag[ch[x][0]]^=1;
tag[ch[x][1]]^=1;
swap(ch[x][0],ch[x][1]);//旋转
tag[x]=0;
}
return ;
}
rotate:将当前节点与它的父亲交换
void rotate(int x) {
int old=f[x],oldf=f[old],whichx=get(x);
pushdown(old);pushdown(x);
ch[old][whichx]=ch[x][whichx^1];
f[ch[old][whichx]]=old;
ch[x][whichx^1]=old;
f[old]=x;
f[x]=oldf;
if(oldf)
ch[oldf][ch[oldf][1]==old]=x;
update(old);update(x);
return ;
}
详细解析:
为了维护Splay序列的规则,我们在交换时有两个规则
1.若当前节点是父亲节点的左儿子,则交换后父亲节点为当前节点的右儿子;反之亦然
2.若当前节点是父亲节点的左儿子,则交换后当前节点的右儿子需要”过继”为父亲节点的左儿子;反之亦然
设当前节点为3号节点,则父亲为2号节点,父亲的父亲为1号节点
因为3号节点为2号节点的左儿子,所以2号节点的右儿子需要”过继”为3号节点的左儿子
因为3号节点为2号节点的左儿子,所以3号节点将成为2号节点的右儿子
同时,因为2号节点是1号节点的左儿子,所以3号节点将成为1号节点的左儿子
splay:将一个节点一直交换直到某个节点处
其实splay操作就是不断的rotate(代码很显然嘛),直到交换至目标位置
void splay(int x,int tar) {
for(int fa;(fa=f[x])!=tar;rotate(x))
if(f[fa]!=tar)
rotate(get(x)==get(fa)?fa:x);
if(!tar)
root=x;
return ;
}
find:查询x的排名 ps:只在以大小为排名时可用
int find(int x) {
int now=root,ans=0;
while(1) {
if(x0];
else {
ans+=(ch[now][0]?size[ch[now][0]]:0);
if(x==key[now]) {
splay(now);
return ans+1;
}
ans+=cnt[now];
now=ch[now][1];
}
}
}
findx:找到排名为x的节点编号
int findx(int x) {
int now=root;
while(1) {
pushdown(now);
if(ch[now][0]&&x<=size[ch[now][0]])
now=ch[now][0];
else {
int tmp=(ch[now][0]?size[ch[now][0]]:0)+1;
if(x<=tmp) return now;
x-=tmp;
now=ch[now][1];
}
}
}
insert:插入一个节点
void insert(int x) {
if(root==0) {
sz++;
ch[sz][0]=ch[sz][1]=f[sz]=0;
root=sz;
size[sz]=cnt[sz]=1;
key[sz]=x;
return ;
}
int now=root,fa=0;
while(1) {
if(x==key[now]) {
cnt[now]++;
update(now);
update(fa);
splay(now);
break;
}
fa=now;
now=ch[now][key[now]if(now==0) {
sz++;
ch[sz][0]=ch[sz][1]=0;
f[sz]=fa;
size[sz]=cnt[sz]=1;
ch[fa][key[fa]break;
}
}
return ;
}
del:删除一个节点
void del(int x) {
int whatever=find(x);
if(cnt[root]>1) {
cnt[root]--;
update(root);
return ;
}
if(!ch[root][0] && !ch[root][1]) {
clear(root);
root=0;
return ;
}
if(!ch[root][0]) {
int oldroot=root;
root=ch[root][1];
f[root]=0;
clear(oldroot);
return ;
}
else if(!ch[root][1]) {
int oldroot=root;
root=ch[root][0];
f[root]=0;
clear(oldroot);
return ;
}
int leftbig=pre(),oldroot=root;
splay(leftbig);
ch[root][1]=ch[oldroot][1];
f[ch[oldroot][1]]=root;
clear(oldroot);
update(root);
return ;
}
pre:寻找root的前驱
前驱,即排名比其小的最大节点
则就为root左儿子的最右侧节点(想想为什么?)
int pre() {
int now=ch[root][0];
while(ch[now][1]) now=ch[now][1];
return now;
}
next:寻找后继
后继,即排名比其大的最小节点
则就为root右儿子的最左侧节点(想想为什么?)
int next() {
int now=ch[root][1];
while(ch[now][0]) now=ch[now][0];
return now;
}
BZOJ 3224 普通平衡树
BZOJ 3223 文艺平衡树