世界真的很大
虽然是treap的裸题,但是不总结一下的话,总感觉不能说完全的掌握,毕竟是新学的东西。
首先是treap的浅谈
1.二叉搜索树
什么是平衡树(二叉排序树,二叉搜索树)?
二叉排序树(Binary Sort Tree)或者是一棵空树;或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二叉排序树。
但是操作里面涉及插入或删除,经过多次之后不见得还能保证二叉搜索树的性质,每次查询不见得还是logn的,我们需要一种操作(几乎成为平衡树的代表标志):旋转(rotate)
还有一种判断是么时候应该旋转的maintain函数。
我们大体上以maintain的不同区分平衡树
treap中如果通过多次插入删除导致数不再平衡了的话,用旋转的方式重新维护平衡树的性质。
左旋:即上图中用x及其子树区替代y的位置,因为x的所有子树的值都是小于y的,而x的右子树的值都是大于x且小于y的,正好在旋转后处于y的左子树,同时我们把y的父节点接到x上,使x成为新的y。
代码:
void left(node *&x)
{
node *y=x->rs;
x->rs=y->ls;
y->ls=x;
x=y;
}
右旋类比左旋
判断是否旋转的理由其实很玄学,rand
通过数学期望方程推算出,通过rand判断是否旋转,成功使树平衡的概率是远远大于失败的概率的,把节点的rand值和储存的值分开保存。代码:
node* newnode(int y)
{
node* nd=++tail;
nd->cnt=y;
nd->key=rand();
nd->ls=nd->rs=0;
return nd;
}
然后是平衡树基本的插入。从根节点开始,依次判断当前节点的值和插入的值的大小,比当前节点的小,就往左子树插入,比当前节点大,就往右子树插入,等于的情况由于个人自己判断分到左还是右,代码:
void insert(node* &nd,int x)
{
if(!nd)
{
nd=newnode(x);
return ;
}
if(nd->cnt==x) return ;
if(x<nd->cnt)
{
insert(nd->ls,x);
if(nd->key<nd->ls->key) right(nd);
}
else
{
insert(nd->rs,x);
if(nd->key<nd->rs->key) left(nd);
}
}
然后每一次插入之前,求其前驱和后驱,比较大小关系加入到ans里,就行了,完整代码:
#include<stdio.h>
#include<algorithm>
using namespace std;
int n;
struct node
{
int cnt,key;
node *ls,*rs;
}pool[100010],*tail=pool,*root;
node* newnode(int y)
{
node* nd=++tail;
nd->cnt=y;
nd->key=rand();
nd->ls=nd->rs=0;
return nd;
}
void right(node *&x)
{
node *y=x->ls;
x->ls=y->rs;
y->rs=x;
x=y;
}
void left(node *&x)
{
node *y=x->rs;
x->rs=y->ls;
y->ls=x;
x=y;
}
void insert(node* &nd,int x)
{
if(!nd)
{
nd=newnode(x);
return ;
}
if(nd->cnt==x) return ;
if(x<nd->cnt)
{
insert(nd->ls,x);
if(nd->key<nd->ls->key) right(nd);
}
else
{
insert(nd->rs,x);
if(nd->key<nd->rs->key) left(nd);
}
}
int before(node *nd,int x)
{
if(!nd) return -(1e7+7);
if(x<nd->cnt) return before(nd->ls,x);
return max(nd->cnt,before(nd->rs,x));
}
int after(node *nd,int x)
{
if(!nd) return 1e7+7;
if(x>nd->cnt) return after(nd->rs,x);
return min(nd->cnt,after(nd->ls,x));
}
int main()
{
freopen ("out.txt", "r", &_iob[0]);
srand(20010216);
while(~scanf("%d",&n))
{
int ans=0,x;
root=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
int pre=before(root,x),post=after(root,x);
if(i==1) ans+=x;
else
ans+=min(x-pre,post-x);
insert(root,x);
}
printf("%d",ans);
}
}
嗯,就是这样。