【模板】可持久化线段树(主席树)

当修改线段树产生新的版本时,对于不需要修改的区间,直接指向原有的点,需要修改的区间,建立新点并连过去。 所以只需要维护m棵线段树的根,动态开点就可以了。
【模板】可持久化数组(可持久化线段树/平衡树) 洛谷P3919

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;
struct Node{
    int val;
    Node *ch[2];
}*root[N];
int n,m,a[N];
void build(Node *&root,int L,int R){
    root=new Node;
    if(L==R){
        root->val=a[L];
        return;
    }
    int mid=L+R>>1;
    build(root->ch[0],L,mid);
    build(root->ch[1],mid+1,R);
}
void insert(Node* &root,int L,int R,int loc,int val){
    Node *tmp=root;
    root=new Node;
    root->ch[0]=tmp->ch[0];
    root->ch[1]=tmp->ch[1];
    if(L==R)    {root->val=val;return;}
    int mid=L+R>>1;
    if(loc<=mid)    insert(root->ch[0],L,mid,loc,val);
    else            insert(root->ch[1],mid+1,R,loc,val);
}
int Query(Node *root,int L,int R,int loc){
    if(L==R)    return root->val;
    int mid=L+R>>1;
    if(loc<=mid)    return Query(root->ch[0],L,mid,loc);
    else            return Query(root->ch[1],mid+1,R,loc);
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;++i)   scanf("%d",&a[i]);
    build(root[0],1,n);
    for(int i=1;i<=m;++i){
        int ver,opt;
        scanf("%d%d",&ver,&opt);
        root[i]=root[ver];
        if(opt==1){
            int loc,val;
            scanf("%d%d",&loc,&val);
            insert(root[i],1,n,loc,val);
        }
        else{
            int loc;
            scanf("%d",&loc);
            printf("%d\n",Query(root[i],1,n,loc));
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zP1nG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值