【模板】可持久化数组(可持久化线段树/平衡树)

本文介绍了一种高效的数据结构——可持久化线段树,并通过实例详细讲解了其构建、更新及查询操作的具体实现过程。适用于解决区间查询与更新问题。

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

题目描述 题目

模板模板
线段与它的历史版本
新的版本只要在历史版本上修改一条路就好了
继续打指针
指针真的好用

代码(可持久化线段树)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int N=1000010;
int n,m,a[N],cnt;
struct node{node* ch[2];int v;};node* T[N];

void build(node* &o,int l,int r)
{
    if(l > r) return ;
    o=new node();
    if(l == r) {o->v=a[l];return ;}
    int mid=(l+r)>>1;
    build(o->ch[0],l,mid);
    build(o->ch[1],mid+1,r);
}

void updata(node* pre,node* &o,int l,int r,int x,int v)
{
    if(l > r) return ;
    o=new node();o->ch[0]=pre->ch[0];o->ch[1]=pre->ch[1];
    if(l == r) {o->v=v;return ;}
    int mid=(l+r)>>1;
    if(x <= mid) updata(pre->ch[0],o->ch[0],l,mid,x,v);
    else updata(pre->ch[1],o->ch[1],mid+1,r,x,v);
}

int query(node* o,int l,int r,int x)
{
    if(l > r) return 0;
    if(l == r) return o->v;
    int mid=(l+r)>>1;
    if(x <= mid) return query(o->ch[0],l,mid,x);
    return query(o->ch[1],mid+1,r,x);
}

int read(){
    int out=0,f=1;char c=getchar();while(c > '9' || c < '0') {if(c == '-') f=-1;c=getchar();}
    while(c <= '9' && c >= '0') {out=(out<<1)+(out<<3)+c-'0';c=getchar();}return out*f;
}

void solve()
{
    n=read(),m=read();
    for(int i=1;i<=n;i++) a[i]=read();
    build(T[0],1,n);
    for(int i=1;i<=m;i++)
    {
        int x=read(),opt=read(),loc=read();
        if(opt == 1)
        {
            int y=read();
            updata(T[x],T[++cnt],1,n,loc,y);
        }
        if(opt == 2) {T[++cnt]=T[x];printf("%d\n",query(T[x],1,n,loc));}
    }
}

int main()
{
    solve();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值