TREAP示例代码(排序)

来源:互联网 发布:智能电视直播软件2017 编辑:程序博客网 时间:2024/06/12 19:02
#include<iostream>#include<cstdio>#include<cstdlib>using namespace std;struct node{int v,w;node *f,*l,*r;node(){v=0;w=rand();f=l=r=NULL;}};node *root;void zig(node *h,node *p){node *t=h->f;h->l=p->r;if(p->r)p->r->f=h;p->r=h;h->f=p;if(t){if(h==t->l)t->l=p;else t->r=p;}else root=p;p->f=t;}void zag(node *h,node *p){node *t=h->f;h->r=p->l;if(p->l)p->l->f=h;p->l=h;h->f=p;if(t){if(h==t->l)t->l=p;else t->r=p;}else root=p;p->f=t;}void insert(node *h,node *p){if(p->v>h->v){if(h->r==NULL){h->r=p;p->f=h;while(p->f!=NULL && p->w<p->f->w){if(p==p->f->l)zig(p->f,p);else zag(p->f,p);}}else insert(h->r,p);}else{if(h->l==NULL){h->l=p;p->f=h;while(p->f!=NULL && p->w<p->f->w){if(p==p->f->l)zig(p->f,p);else zag(p->f,p);}}else insert(h->l,p);}}void read(int &x){x=0;char c=getchar();while(c<'0' || c>'9')c=getchar();while(c>='0' && c<='9'){x=x*10+c-'0';c=getchar();}}void out(node *h){if(h){out(h->l);printf("%d ",h->v);out(h->r);}}int main(){int i,j,k,m,n;node *p;srand(34234);cin>>n;cin>>k;root=new node;root->v=k;for(i=2;i<=n;i++){read(k);p=new node;p->v=k;insert(root,p);}out(root);return 0;}

原创粉丝点击