跳到正文

算法·理论

可持久化线段树

ToastBread约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年12月15日
收录
2026年12月2日
更新
2026年12月2日
篇幅
约 4 分钟

版本

  1. v1当前

可持久化线段树,顾名思义,就是可持久化的线段树。

主要运用了动态开点和优化思想。

P3919

一个比较暴力的想法是,对于每一次操作都新建一棵树,但这是 O(n2)O(n^2) 的。

不妨每一次只修改部分节点,对于左/右子树和原树一样的就不做修改,把对应子树直接指向原子树。否则,就开一棵和原子树一样的新子树,在新子树上做修改,再把原树的指针改一下就可以了。

比较难理解的是代码的 & 指针操作,指针比较巧妙,相当于在子树做处理的时候才做父亲修改子树编号的操作。

最后的树大小约为 4n+mlog⁡n4n+m\log n。

C++
#include<bits/stdc++.h>
using namespace std;
//#define int long long
int a[1000005],n,m,op,x,y,z,cnt,ver,rtid[1000005];
struct node
{
    int l,r,ls,rs,dat;
};
node t[25000005];
void pushdown(int p)//单点查询,无需pushdown/pushup
{
    return;
}
void pushup(int p)
{
    //t[p].dat=t[p*2].dat+t[p*2+1].dat;
    return;
}
void build(int &p,int l,int r)
{
	cnt++;//开点
	p=cnt;//这里的 p 是指针,相当于修改父亲节点传来的 t[p].ls/rs,使它指向子树自己
    t[p].l=l;
    t[p].r=r;
    if(l==r)
    {
        t[p].dat=a[l];
        return;
    }
    int mid=(l+r)/2;
    build(t[p].ls,l,mid);
    build(t[p].rs,mid+1,r);
    pushup(p);
    return;
}
void update(int &p,int lst,int l,int r,int d)
{
	cnt++;//开点
	p=cnt;
	t[p]=t[lst];
    if(t[p].l>=l&&t[p].r<=r)
    {
        t[p].dat=d;
        return;
    }
    pushdown(p);
    int mid=(t[p].l+t[p].r)/2;
    if(l<=mid) update(t[p].ls,t[p].ls,l,r,d);
    if(r>mid) update(t[p].rs,t[p].rs,l,r,d);
    pushup(p);
    return; 
}
int query(int p,int l,int r)
{
    if(t[p].l>=l&&t[p].r<=r)
    {
        return t[p].dat;
    }
    pushdown(p);
    int mid=(t[p].l+t[p].r)/2,res=0;
    if(l<=mid) res+=query(t[p].ls,l,r);
    if(r>mid) res+=query(t[p].rs,l,r);
    return res;
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
    cin>>n>>m;
    for(int i = 1; i <= n; i++) cin>>a[i];
    build(rtid[0],1,n);//rtid是对应版本根的位置
    for(int i = 1; i <= m; i++)
    {
        cin>>ver>>op;
        if(op==1)
        {
            cin>>x>>z;
            update(rtid[i],rtid[ver],x,x,z);
        }
        else
        {
            cin>>x;
            cout<<query(rtid[ver],x,x)<<'\n';
            rtid[i]=rtid[ver];//注意此时要不做修改,把这个版本的根节点改为以前版本的根节点
        }
    }
}
原文