【模板】Treap

#include<iostream>      
#include<cstdio>
using namespace std;

struct treap
{
  int num,size,fix;
  treap* ch[2];
  treap(int x)
  {
    num=x;
    size=1;
    fix=rand();
    ch[0]=ch[1]=NULL;
  }  
  int cmp(int x)const
  {
    if(x==num)return -1;
    return x>num ? 1:0;    
  }
  void up()
  {
    size=1;
    if(ch[0]!=NULL)size+=ch[0]->size;
    if(ch[1]!=NULL)size+=ch[1]->size;     
  }
};
treap* root=NULL;


inline void rotate(treap* &x,int d)
{
  treap* t=x->ch[d^1];
  x->ch[d^1]=t->ch[d];
  t->ch[d]=x;
  x->up();
  t->up();
  x=t;
}

bool f(treap* x,int num)
{
  int d=0;
  while(NULL!=x)
  {
    d=x->cmp(num);
    if(d==-1)return true;
    x=x->ch[d];              
  }     
  return false;
}

void insert(treap* &x,int num)
{
  if(NULL==x)x=new treap(num);           
  else 
  {
    int d=x->cmp(num);
    insert(x->ch[d],num);
    if(x->fix > x->ch[d]->fix)
      rotate(x,d^1);
  }
  x->up();
}
//*
void del(treap* &x,int num)
{
  int d=x->cmp(num);
  if(d!=-1)del(x->ch[d],num);
  else 
  {
    if(NULL==x->ch[0])x=x->ch[1];
    else if(NULL==x->ch[1])x=x->ch[0];
    else 
    {
      int k= x->ch[0]->fix > x->ch[1]->fix ? 0:1;
      rotate(x,k);
      del(x->ch[k],num);
    }     
  }
  if(NULL!=x)x->up();  
}
//*/
void print(treap* x)
{
  if(NULL==x)return ;
  print(x->ch[0]);
  printf("%d  ",x->num);
  print(x->ch[1]);     
}
//*
void kth(treap* x,int k)
{
  if(NULL==x||k<=0||x->size<k)printf("NULL\n");
  else if(NULL==x->ch[0]&&k==1)printf("%d\n",x->num);
  else if(NULL==x->ch[0])kth(x->ch[1],k-1);
  else if(x->ch[0]->size+1==k)printf("%d\n",x->num);
  else if(x->ch[0]->size>=k)kth(x->ch[0],k);
  else kth(x->ch[1],k-1-x->ch[0]->size);
}
//*/

int rank(treap* x,int num)
{
  int ans=0;
  if(NULL!=x->ch[0])ans+=x->ch[0]->size;
  if(num==x->num)return ans+1;
  else if(num<x->num)return rank(x->ch[0],num);
  else return ans+1+rank(x->ch[1],num);
}

int main()
{
  int n=0;
  scanf("%d",&n);
  int use[100];
  for(int i=1;i<=n;i++)
  {
    scanf("%d",&use[i]);
    if(f(root,use[i])==false)
      insert(root,use[i]);
  }  
  
  print(root);
  
  int tmp=0,k;
  //*
  while(~scanf("%d%d",&k,&tmp))
  {
    
  }
  //*/
    
  while(1);
  return 0;    
    
}

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值