原理
https://www.cnblogs.com/liuwenyao/p/10994589.html
模板
#include <iostream>//可持久化数组 https://www.cnblogs.com/liuwenyao/p/10994589.html
#include <cstdio>//板子题https://www.luogu.com.cn/problem/P3919
#include <algorithm>//版本号从0开始 a[]数组从1开始
#include <cstring>
#define ls left, mid, tree[root].l
#define rs mid + 1, right, tree[root].r
const int N=6e7+10;
using namespace std;
int n, m, cnt, a[N], r[N];//n为数组长度、m为操作个数、cnt为树的下标、a[]为原数组、r[]为历史版本根节点
struct data {
int l, r, dat;//左节点、右节点、数据
} tree[N];
inline int newroot(int root) {//建立新的与上个版本一模一样的树
tree[++cnt] = tree[root];
return cnt;
}
int build(int left, int right, int root) {//建树 除了叶子结点,其他节点数据均为空值(因为不需要维护数据)
root = ++cnt;
if (left == right) {
tree[root].dat = a[left];
return cnt;
}
int mid = (left + right) >> 1;
tree[root].l = build(ls);//ls -> left, mid, tree[root].l
tree[root].r = build(rs);//rs -> mid + 1, right, tree[root].r
return root;
}
int update(int left, int right, int root, int pos, int add) {//单点更新 更新后a[pos]的值为add
root = newroot(root);//先建新版本的树
if (left == right) {//递归边界
tree[root].dat = add;
return root;
}
//注意root << 1并不是root该节点的左儿子,因为之间有新节点,所以要用tree[root].l和tree[root].r来代替。
int mid = (left + right) >> 1;
if (pos <= mid) tree[root].l = update(ls, pos, add);//访问左子树
else tree[root].r = update(rs, pos, add);//访问右子树
return root;
}
int query(int left, int right, int root, int pos) {//询问某历史版本下pos的值
root = newroot(root);
int mid = (left + right) >> 1;
if (left == right) return tree[root].dat;
if (pos <= mid) return query(ls, pos);
else return query(rs, pos);
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
r[0] = build(1, n, 0);//build(1, n, 0); //r[x]是第x版本上的根节点,而线段树中的几个基本操作返回的也就是根节点。
for (int i = 1; i <= m; i++) {
int a, b, c, d;
scanf("%d%d%d", &a, &b, &c);
if (b == 1) {
scanf("%d", &d);
r[i] = update(1, n, r[a], c, d);
} else {
printf("%d\n", query(1, n, r[a], c));
r[i] = r[a];
}
}
return 0;
}