【模板】splay维护序列

题目大意:维护一个长度为 N 的序列,支持单点插入,单点询问。

注意事项如下:

  • build 函数中要记得初始化 fa。
  • 插入两个端点值。

代码如下

#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define all(x) x.begin(),x.end()
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=1e5+10;

inline int read(){
    int x=0,f=1;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
    do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
    return f*x;
}

int n,m,a[maxn];
struct node{
    #define ls(x) t[x].ch[0]
    #define rs(x) t[x].ch[1]
    int ch[2],fa,val,size;
}t[maxn<<1];
int tot,root;
inline void pushup(int o){t[o].size=t[ls(o)].size+t[rs(o)].size+1;}
inline bool get(int o){return o==rs(t[o].fa);}
inline void rotate(int o){
    int fa=t[o].fa,gfa=t[fa].fa,d1=get(o),d2=get(fa);
    t[fa].ch[d1]=t[o].ch[d1^1],t[t[o].ch[d1^1]].fa=fa;
    t[fa].fa=o,t[o].ch[d1^1]=fa;
    t[o].fa=gfa,t[gfa].ch[d2]=o;
    pushup(fa),pushup(o);
}
inline void splay(int o,int goal){
    while(t[o].fa!=goal){
        int fa=t[o].fa,gfa=t[fa].fa;
        if(gfa!=goal)get(fa)==get(o)?rotate(fa):rotate(o);
        rotate(o);
    }
    if(!goal)root=o;
}
int find(int o,int k){
    if(k<=t[ls(o)].size)return find(ls(o),k);
    else if(k>t[ls(o)].size+1)return find(rs(o),k-t[ls(o)].size-1);
    else return o;
}
int build(int fa,int l,int r){
    if(l>r)return 0;
    int o=++tot;
    int mid=l+r>>1;
    t[o].val=a[mid],t[o].fa=fa;
    ls(o)=build(o,l,mid-1),rs(o)=build(o,mid+1,r);
    return pushup(o),o;
}
void insert(int pos,int val){
    int x=find(root,pos-1),y=find(root,pos);
    splay(x,0),splay(y,x);
    ++tot,t[tot].val=val,t[tot].size=1,t[tot].fa=y,ls(y)=tot;
    pushup(y),pushup(x);
}

void read_and_parse(){
    n=m=read();
    for(int i=2;i<=n+1;i++)a[i]=read();
    root=build(0,1,n+2);
}
void solve(){
    while(m--){
        int opt=read(),l=read(),r=read(),c=read();
        if(opt==0)insert(l+1,r);
        else if(opt==1)printf("%d\n",t[find(root,r+1)].val);
    }
}
int main(){
    read_and_parse();
    solve();
    return 0;
}

转载于:https://www.cnblogs.com/wzj-xhjbk/p/10615127.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值