跳到正文

算法·理论

可持久化数组学习笔记

Sternenlicht约 5 分钟
原文

这是 2026年1月21日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2022年6月5日
收录
2026年1月21日
更新
2026年11月14日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

参考视频:【AgOHの数据结构】可持久化数组

例题:P3919 【模板】可持久化线段树 1(可持久化数组)

朴素算法:开一个二维数组 ai,ja_{i,j} 记录第 ii 个版本的第 jj 个数是什么,会 MLEMLE。

乱搞做法:roperope。头文件 #include <ext/rope>,命名空间 using namespace __gnu_cxx;。一个块状链表,支持 O(1)O(1) 复制!即可对每一个操作复制一个 roperope 当做新版本,且炸不了空间,但容易 TLETLE。博客


可持久化数组:可以支持回退,访问之前版本的数组。

正解:用主席树维护一个普通线段树。

  1. 用原数组建立一个普通线段树。

  2. 每次对数组的某一版本的某一位置进行修改,相当于以主席树的相应版本的相应位置为模板,新建执行一次单点修改的新版本。访问同理。

注意:

  1. 需要建树操作,因为普通线段树的初始版本有数值,所以要先用原数组建立一棵线段树,然后再操作。

  2. 让 rootnow=roothistoryroot_{now}=root_{history},访问当前版本时就会访问到历史版本上去,相当于复制了一遍。

C++
#include <bits/stdc++.h>
#define LL long long
#define endl '\n'
#define lowbit(x) (x&-x)
#define ls(x) (x<<1)
#define rs(x) (x<<1|1)
#define INF 0x3f3f3f3f
namespace IO{
	inline LL read(){
	    LL x=0,f=1;char ch=getchar();
	    for (;!isdigit(ch);ch=getchar())if (ch=='-')f=-1;
	    for (;isdigit(ch);ch=getchar())x=(x<<3)+(x<<1)+(ch^48);
	    return x*f;
	}
	inline void write(LL x,char c='\n'){
	    if (x){
	    	if (x<0)x=-x,putchar('-');
	    	char a[30];short l;
	    	for (l=0;x;x/=10)a[l++]=x%10^48;
	    	for (l--;l>=0;l--)putchar(a[l]);
		}
		else putchar('0');putchar(c);
	}
	inline char getc(){
		char ch=getchar();
		while (isspace(ch))ch=getchar();
		return ch;
	}
}
using namespace IO;
using namespace std;

const int N = 1e6+10;
//与主席树一样,不解释 
struct node{int l,r,val;}tree[N<<5];
int a[N],root[N],cnt;
void build(int &now,int l,int r){
	now=++cnt;
	if (l==r)return tree[now].val=a[l],void();//到叶子结点,赋值
	int mid=(l+r)>>1;
	build(tree[now].l,l,mid);
	build(tree[now].r,mid+1,r);
}
void update(int &now,int pre,int l,int r,int x,int val){
	tree[now=++cnt]=tree[pre];//复制历史版本
	if (l==r)return tree[now].val=val,void();//到叶子结点,赋值,退出
	int mid=(l+r)>>1;
	if (x<=mid)update(tree[now].l,tree[pre].l,l,mid,x,val);
	else	 update(tree[now].r,tree[pre].r,mid+1,r,x,val);
}
int query(int now,int l,int r,int x){
	if (l==r)return tree[now].val;//到叶子结点,直接返回当前结点的值
	int mid=(l+r)>>1;
	if (x<=mid)return query(tree[now].l,l,mid,x);
	else	 return query(tree[now].r,mid+1,r,x); 
}
int main(){
	int n=read(),m=read();
	for (int i=1;i<=n;i++)a[i]=read();
	build(root[0],1,n);//建树
	for (int i=1;i<=m;i++){
		int v=read(),opt=read(),x=read(),y;
		if (opt==1)y=read(),update(root[i],root[v],1,n,x,y);
		if (opt==2)write(query(root[v],1,n,x)),root[i]=root[v];
	} 
    return 0;
}