fhq_Treap——模板整理

本文介绍了一种高效的数据结构——FHQ Treap,并提供了其核心实现代码。该Treap支持快速插入、删除及查找中位数等操作,适用于解决涉及动态数据集排序和统计的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

好写,而且能可持久化。

#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
struct node{
    int key,fix,size; node* ch[2];
    node(int tkey=2e+9+5,node* son=NULL){ key=tkey; fix=(rand()<<16)+rand(); size=1; ch[0]=ch[1]=son; }
    void maintain(){ size=ch[0]->size+ch[1]->size+1; }
} nil, *null=&nil, *root=null;
typedef node* P_node;
void null_init(){ null->fix=-1e+9; null->size=0; null->ch[0]=null->ch[1]=null; } 
P_node Merge(P_node p1,P_node p2){
    if(p1==null||p2==null) return p1==null?p2:p1;
    if(p1->fix>p2->fix){ p1->ch[1]=Merge(p1->ch[1],p2); p1->maintain(); return p1; } 
                   else{ p2->ch[0]=Merge(p1,p2->ch[0]); p2->maintain(); return p2; } 
}
void Split(P_node p,int val,P_node &Left,P_node &Right){ // (-oo,val]  (val,+oo)
    if(p==null){ Left=Right=null; return; }
    if(p->key<=val) Left=p, Split(p->ch[1],val,p->ch[1],Right);
               else Right=p, Split(p->ch[0],val,Left,p->ch[0]);
    p->maintain();
}
void Insert(int tkey){
    P_node Left,Right; Split(root,tkey-1,Left,Right);
    root=Merge(Left,Merge(new node(tkey,null),Right));
}
void Erase(int tkey){
    P_node Left,Right,mid;
    Split(root,tkey-1,Left,Right); Split(Right,tkey,mid,Right);
    root=Merge(Left,Merge(Merge(mid->ch[0],mid->ch[1]),Right));
}
int Kth(P_node p,int k){
    if(p->ch[0]->size==k-1) return p->key;
    if(p->ch[0]->size>=k) return Kth(p->ch[0],k);
    return Kth(p->ch[1],k-p->ch[0]->size-1);
}
int get_edge(P_node p,int k){ while(p->ch[k]!=null) p=p->ch[k]; return p->key; }
int n;
int main(){
    freopen("fhq_treap.in","r",stdin);
    freopen("fhq_treap.out","w",stdout);
    null_init(); srand(233);
    root=Merge(new node(-(2e+9+5),null),new node(2e+9+5,null));
    scanf("%d",&n);
    while(n--){
        int pd,x; P_node Left,Right; scanf("%d%d",&pd,&x);
        if(pd==1) Insert(x); else
        if(pd==2) Erase(x); else
        if(pd==3){ Split(root,x-1,Left,Right); printf("%d\n",Left->size+1-1); root=Merge(Left,Right); } else
        if(pd==4){ x++; printf("%d\n",Kth(root,x)); } else
        if(pd==5){ Split(root,x-1,Left,Right); printf("%d\n",get_edge(Left,1)); root=Merge(Left,Right); } else
        if(pd==6){ Split(root,x,Left,Right); printf("%d\n",get_edge(Right,0)); root=Merge(Left,Right); }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值