您的位置:首页 > 其它

平衡树:treap学习笔记(1)

2017-11-16 21:10 267 查看
平衡树是基于二叉查找树的一个数据结构。他的左右子树高度差不超过1。

二叉查找树插入时最坏情况下退化成一条链,查找复杂度O(n)。我们可以用平衡树来维护使得左右子树平衡,复杂度在O(logn)。

怎么平衡呢?我们用旋转来实现。在treap中有左旋和右旋两个操作。

左旋:将自己的左儿子变成父亲节点的右儿子,父亲节点变成自己的左儿子。

右旋是对称的。(代码中的p是这里说的父亲节点。

treap=tree+heap。他的优先级(随机数)以堆的形式排布,值域是二叉查找树的形式。

其实我觉得平衡树最难的部分是查找qaq。。。可能我还是太菜了。

#include<bits/stdc++.h>
using namespace std;

const int MAXN=2e5+5;

int my_rand(){
static int seed=623;
return seed=int(seed*48271LL%2147483647);
}

struct treap{
int size[MAXN],lson[MAXN],rson[MAXN],prio[MAXN],w[MAXN];
int cnt1,rt;
void mem(){
cnt1=0,rt=0;
memset(w, 0, sizeof(w));
memset(prio, 0, sizeof(prio));
memset(size, 0, sizeof(size));
memset(lson, 0, sizeof(lson));
memset(rson, 0, sizeof(rson));
}
inline void pushup(int o){size[o]=size[lson[o]]+size[rson[o]]+1;}
inline void zuo(int &p){
int tem=rson[p];
rson[p]=lson[tem];
lson[tem]=p;
size[tem]=size[p];
pushup(p);
p=tem;
}
inline void you(int &p){
int tem=lson[p];
lson[p]=rson[tem];
rson[tem]=p;
size[tem]=size[p];
pushup(p);
p=tem;
}
inline void insert(int &p,int x){
if(!p){
p=++cnt;w[p]=x;size[p]=1;prio[p]=my_rand();return;
}
size[p]++;
insert((x>=w[p])?rson[p]:lson[p],x);
if(lson[p]&&prio[lson[p]]<prio[p])you(p);
if(rson[p]&&prio[rson[p]]<prio[p])zuo(p);
}
inline void del(int &p,int x){
size[p]--;
if(x==w[p]){
if(!lson[p]&&!rson[p]){p=0;return;}
if(!lson[p]||!rson[p]){p=lson[p]+rson[p];return;}
if(prio[lson[p]]<prio[rson[p]]){
you(p);
del(rson[p],x);
return;
}
else {
zuo(p);
del(lson[p],x);
return;
}
}
del((x>=w[p])?rson[p]:lson[p],x);
}
inline int rank(int &p,int x){
if(!p)return 0;
int ans=0;
if(w[p]<x)ans+=size[lson[p]]+1+rank(rson[p],x);
else ans=rank(lson[p],x);
return ans;
}
inline int rankshu(int &p,int x){
if(x==size[lson[p]]+1)return w[p];
if(size[lson[p]]+1<x) return rankshu(rson[p],x-size[lson[p]]-1);
else return rankshu(lson[p],x);
}
inline int rankpre(int &p,int x){
if(!p)return 0;
if(w[p]>=x)return rankpre(lson[p],x);
int tem=rankpre(rson[p],x);
if(!tem)return w[p];
else return tem;
}
inline int rankhou(int &p,int x){
if(!p)return 0;
if(w[p]<=x)return rankhou(rson[p],x);
int tem=rankhou(lson[p],x);
if(!tem)return w[p];
else return tem;
}
}treap;

int n;
int main(){
//  freopen("1.in","r",stdin);
//  freopen("1.out","w",stdout);
scanf("%d",&n);
treap.mem();
for(int i=1;i<=n;i++){
int opt, x;
scanf("%d%d", &opt, &x);
if(opt==1)treap.insert(treap.rt,x);
if(opt==2)treap.del(treap.rt,x);
if(opt==3)p
4000
rintf("%d\n",treap.rank(treap.rt,x)+1);
if(opt==4)printf("%d\n",treap.rankshu(treap.rt,x));
if(opt==5)printf("%d\n",treap.rankpre(treap.rt,x));
if(opt==6)printf("%d\n",treap.rankhou(treap.rt,x));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: