treap

来源:互联网 发布:淘宝联盟编辑分享文案 编辑:程序博客网 时间:2024/06/07 06:29
#include<iostream>#include<cmath>#include<cstdio>#include<cstdlib>#include<cstring>#include<algorithm>using namespace std;struct node{int v,w;/* vΪÊý×Ö£¬wΪȨÖØ */ struct node *h,*l,*r;node(){v=w=0;l=r=NULL;}};void rotate_left(struct node *a,struct node *b){b->h=a->h;if(b->h!=NULL){if(b->h->l==a)b->h->l=b;else b->h->r=b;}a->r=b->l;if(b->l!=NULL)b->l->h=a;b->l=a;a->h=b;}void rotate_right(struct node *a,struct node *b){b->h=a->h;if(b->h!=NULL){if(b->h->l==a)b->h->l=b;else b->h->r=b;}a->l=b->r;if(b->r!=NULL)b->r->h=a;b->r=a;a->h=b;}struct node *s,*q,*p;void insert(struct node *t,int k){if(k<t->v){if(t->l==NULL){q=new node;q->v=k;q->w=rand();q->h=t;t->l=q;p=q;while(p->h!=NULL && p->w<q->h->w){if(p->h->l==p)rotate_right(p->h,p);elserotate_left(p->h,p);if(p->h=NULL) s=p;}}elseinsert(t->l,k);}else{if(t->r==NULL){q=new node;q->v=k;q->w=rand();q->h=t;t->r=q;p=q;while(p->h!=NULL && p->w<q->h->w){if(p->h->l==p)rotate_right(p->h,p);elserotate_left(p->h,p);if(p->h=NULL) s=p;}}elseinsert(t->r,k);}}void out(struct node *t){if(t==NULL)return;out(t->l);printf("%d ",t->v);out(t->r);}int main(){int i,j,k,m,n;srand(1474);scanf("%d",&n);scanf("%d",&k);s=new node;s->v=k;s->w=rand();s->h=NULL;for(i=2;i<=n;i++){scanf("%d",&k);insert(s,k);}out(s);}


1 0
原创粉丝点击