#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node{
int x,w;
struct node *fa,*lc,*rc;
node(){
x=0;w=0;fa=NULL;lc=NULL;rc=NULL;
}
};
node *root;
void ZAG(node *a,node *b){
node *tmp=a->fa;
a->lc=b->rc;if(b->rc)b->rc->fa=a;
b->rc=a;a->fa=b;
if(tmp){
if(a==tmp->lc)tmp->lc=b;
else tmp->rc=b;
}else root=b;
b->fa=tmp;
}
void ZIG(node *b,node *a){
node *tmp=b->fa;
b->rc=a->lc;if(a->lc)a->lc->fa=b;
a->lc=b;b->fa=a;
if(tmp){
if(b==tmp->lc)tmp->lc=a;
else tmp->rc=a;
}else root=a;
a->fa=tmp;
}
void insert(node *h,node *q){
if(q->x>h->x){
if(h->rc==NULL){
h->rc=q;q->fa=h;
while(q->fa!=NULL && q->w<q->fa->w){
if(q==q->fa->lc)ZAG(q->fa,q);
else ZIG(q->fa,q);
}
}
else insert(h->rc,q);
}else{
if(h->lc==NULL){
h->lc=q;q->fa=h;
while(q->fa!=NULL && q->w<q->fa->w){
if(q==q->fa->lc)ZAG(q->fa,q);
else ZIG(q->fa,q);
}
}
else insert(h->lc,q);
}
}
void out(node *h){
if(h){
out(h->lc);
printf("%d ",h->x);
out(h->rc);
}
}
int main(){
int i,j,k,m,n;
node *h,*p,*q;
cin>>n;
srand(4654);
cin>>k;
root=new node;root->x=k;root->w=rand();
for(i=2;i<=n;i++){
scanf("%d",&k);
q=new node;q->x=k;q->w=rand();
insert(root,q);
}
out(root);
return 0;
}
利用Treap排序
最新推荐文章于 2024-05-06 15:54:15 发布