题目链接:https://www.luogu.com.cn/problem/P3919
解题思路:
主席树纯模板题。
示例程序:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000010;
struct Tree {
int l, r, val;
} tree[maxn*40];
int n, m, root[maxn], tot;
void build(int l, int r, int& rt) {
rt = ++tot;
if (l == r) {
cin >> tree[rt].val;
return;
}
int mid = (l + r) / 2;
build(l, mid, tree[rt].l);
build(mid+1, r, tree[rt].r);
}
void update(int p, int val, int l, int r, int pt, int &rt) {
tree[rt = ++tot] = tree[pt];
if (l == r) {
tree[rt].val = val;
return;
}
int mid = (l + r) / 2;
if (p <= mid) update(p, val, l, mid, tree[pt].l, tree[rt].l);
else update(p, val, mid+1, r, tree[pt].r, tree[rt].r);
}
int query(int p, int l, int r, int rt) {
if (l == r) return tree[rt].val;
int mid = (l + r) / 2;
if (p <= mid) return query(p, l, mid, tree[rt].l);
else return query(p, mid+1, r, tree[rt].r);
}
int main() {
ios::sync_with_stdio(0);
cin >> n >> m;
build(1, n, root[0]);
for (int i = 1; i <= m; i ++) {
int v, op, p, val;
cin >> v >> op >> p;
if (op == 1) {
cin >> val;
update(p, val, 1, n, root[v], root[i]);
}
else { // op == 2
root[i] = root[v];
cout << query(p, 1, n, root[i]) << endl;
}
}
return 0;
}