当前位置: 代码迷 >> 综合 >> treap 普通平衡树
  详细解决方案

treap 普通平衡树

热度:13   发布时间:2023-12-08 15:07:33.0

     普通treap中最普通的板子(数组版)

      

#include<stdio.h>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cmath>
#define inf 10000000
using namespace std;
struct tree
{int l,r,size,tot,h,rd;
} t[100005];
int n,root,fro,bac,hh;
void l_swap(int &root)
{int k=t[root].r;t[root].r=t[k].l;t[k].l=root;t[k].size=t[root].size;t[root].size=t[t[root].l].size+t[t[root].r].size+t[root].tot;root=k;
}
void r_swap(int &root)
{int k=t[root].l;t[root].l=t[k].r;t[k].r=root;t[k].size=t[root].size;t[root].size=t[t[root].l].size+t[t[root].r].size+t[root].tot;root=k;
}
void build(int &root,int k)
{if(!root){root=++hh;t[root].h=k;t[root].size=t[root].tot=1;t[root].rd=rand();return;}t[root].size++;if(t[root].h==k)t[root].tot++;else{if(t[root].h>k){build(t[root].l,k);if(t[t[root].l].rd<t[root].rd);r_swap(root);}else{build(t[root].r,k);if(t[t[root].r].rd<t[root].rd)l_swap(root);}}
}
void del(int &root,int k)
{if(!root)return;if(t[root].h==k){if(t[root].tot>1){t[root].tot--;t[root].size--;return;}if(t[root].l*t[root].r==0)root=t[root].l+t[root].r;else{if(t[t[root].l].rd<t[t[root].r].rd)r_swap(root);elsel_swap(root);del(root,k);}}else{t[root].size--;if(k>t[root].h)del(t[root].r,k);else del(t[root].l,k);}
}
void FRO(int &root,int k)
{if(!root)return;if(t[root].h<k){fro=t[root].h;FRO(t[root].r,k);}else FRO(t[root].l,k);
}
void BAC(int &root,int k)
{if(!root)return;if(t[root].h>k){bac=t[root].h;BAC(t[root].l,k);}else BAC(t[root].r,k);
}
int num(int &root,int k)
{if(!root)return 0;if(t[root].h==k)return t[t[root].l].size+1;else{if(t[root].h>k)return num(t[root].l,k);else  return t[t[root].l].size+t[root].tot+num(t[root].r,k);}
}
int Q(int &root,int k)
{if(!root)return 0;if(t[t[root].l].size+1<=k&&t[t[root].l].size+t[root].tot>=k)return t[root].h;if(t[t[root].l].size>=k)return Q(t[root].l,k);if(t[t[root].l].size<k)return Q(t[root].r,k-t[root].tot-t[t[root].l].size);
}
int yjn()
{
//	 freopen("phs.in","r",stdin);//  freopen("phs.out","w",stdout);scanf("%d",&n);int x,y;for(int i=1;i<=n;i++){scanf("%d%d",&x,&y);if(x==1)build(root,y);if(x==2)del(root,y);if(x==3){printf("%d\n",num(root,y));}if(x==4){printf("%d\n",Q(root,y));}if(x==5){fro=-inf;FRO(root,y);printf("%d\n",fro);}if(x==6){bac=-inf;BAC(root,y);printf("%d\n",bac);}}
}
int qty=yjn();
int main(){;}