Treap平衡树

来源:互联网 发布:湖南省网络作家协会 编辑:程序博客网 时间:2024/05/16 09:41
#include<stdio.h>  #include<stdlib.h>  #include<string.h>  #include<iostream>  #include<algorithm>  using namespace std;    struct node{      int x,w;      struct node *l,*r,*f;      node(){          x=0;          w=(int)rand()*1.0/32767*2147483647;;          l=r=f=NULL;      }  };  struct node *h,*p,*q,*v,*tmp;   void left(struct node *u){      v=u->f;      if (v==h)          h=u;      v->r=u->l;      if (u->l!=NULL)          u->l->f=v;      u->f=v->f;      if (v->f!=NULL)          if (v==v->f->l)              v->f->l=u;          else v->f->r=u;      v->f=u;      u->l=v;  }  void right(struct node *u){      v=u->f;      if (v==h)          h=u;      v->l=u->r;      if (u->r!=NULL)          u->r->f=v;      u->f=v->f;      if (v->f!=NULL)          if (v==v->f->l)              v->f->l=u;          else v->f->r=u;      v->f=u;      u->r=v;  }  void insert(struct node *f,int k){      if (k<f->x){          if (f->l==NULL){              p=new node;              p->x=k;              p->f=f;              f->l=p;              while (p->f!=NULL && p->w<p->f->w)                  if (p==p->f->l)                      right(p);                  else left(p);          }else insert(f->l,k);      }else{          if (f->r==NULL){              p=new node;              p->x=k;              p->f=f;              f->r=p;              while (p->f!=NULL && p->w<p->f->w)                  if (p==p->f->l)                      right(p);                  else left(p);          }else insert(f->r,k);      }  }  void out(struct node *f){      if (f->l!=NULL) out(f->l);      printf("%d ",f->x);      if (f->r!=NULL) out(f->r);      delete f;  }bool find(struct node *f,int k){if (k==f->x)return 1;if (k<f->x){if (f->l==NULL)return 0;else find(f->l,k);}else{if (f->r==NULL)return 0;else find(f->r,k);}}bool del(struct node *f,int k){if (k==f->x){while (f->l!=NULL || f->r!=NULL){if (f->l==NULL || (f->r!=NULL && f->r->w<f->l->w))left(f->r);else right(f->l);}return 1;}if (k<f->x){if (f->l==NULL)return 0;else del(f->l,k);}else{if (f->r==NULL)return 0;else del(f->r,k);}}  int main(){      int i,j,k,m,n;      srand(32767);      h=new node;      h->f=NULL;      scanf("%d",&n);      scanf("%d",&h->x);      for (i=2;i<=n;i++){          scanf("%d",&k);          insert(h,k);      }scanf("%d",&m);for (i=1;i<=m;i++){scanf("%d",&k);printf("%d",find(h,k));}scanf("%d",&m);for (i=1;i<=m;i++){scanf("%d",&k);printf("%d",del(h,k));}    return 0;  }

1 2
原创粉丝点击