#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
struct T{
int l,r,f;
int w,z;
}a[100000+10];
int root,cnt;
void r_rot(int x,int y){
int t=a[y].f;
a[y].l=a[x].r;
a[a[x].r].f=y;
a[x].r=y;
a[y].f=x;
if(a[t].l==y)a[t].l=x;
else a[t].r=x;
a[x].f=t;
}
void l_rot(int x,int y){
int t=a[y].f;
a[y].r=a[x].l;
a[a[x].l].f=y;
a[x].l=y;
a[y].f=x;
if(a[t].l==y)a[t].l=x;
else a[t].r=x;
a[x].f=t;
}
void insert(int u,int k){
int p;
if(!u)return ;
if(a[u].z<k){
if(!a[u].r){
a[++cnt].f=u;
a[cnt].w=rand();
a[u].r=cnt;
a[cnt].z=k;
p=cnt;
while(a[p].f!=0&&a[p].w>=a[a[p].f].w){
if(p==a[a[p].f].l)r_rot(p,a[p].f);
else l_rot(p,a[p].f);
}
if(a[p].f==0)root=p;
}
else insert(a[u].r,k);
}
else if(a[u].z>=k){
if(!a[u].l){
a[++cnt].f=u;
a[cnt].w=rand();
a[u].l=cnt;
a[cnt].z=k;
p=cnt;
while(a[p].f!=0&&a[p].w>=a[a[p].f].w){
if(p==a[a[p].f].l)r_rot(p,a[p].f);
else l_rot(p,a[p].f);
}
if(a[p].f==0)root=p;
}
else insert(a[u].l,k);
}
}
void out(int n){
if(!n)return ;
out(a[n].l);
printf("%d ",a[n].z);
out(a[n].r);
}
int main(){
int i,j,k,m,n;
scanf("%d",&n);
scanf("%d",&k);
srand(4225);
a[1].z=k;
a[1].f=0;
a[1].w=rand();
root=1;
cnt=1;
for(i=2;i<=n;i++){
scanf("%d",&k);
insert(root,k);
}
out(root);
return 0;
}
Treap
最新推荐文章于 2022-02-10 23:08:07 发布