#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;
}
【模板】Treap
最新推荐文章于 2024-10-16 07:16:00 发布