跳到正文

个人记录

可持久化数组

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

文章信息

收录
2025年12月12日
更新
2026年5月20日
篇幅
约 4 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>

using namespace std;
int n, m;

template<typename Tp, size_t Nb>
class presidentTree {
	private:
		struct node {
			Tp value;
			node *left, *right;

			node() : value(), left(nullptr), right(nullptr) {};
		};
		vector<node*> roots {nullptr};

		void build(const auto &a, int s, int t, node *&p) {
			if (!p) {
				p = new node();
			}

			if (s == t) {
				p->value = a[s];
			} else {
				int mid = (s + t) >> 1;
				build(a, s, mid, p->left);
				build(a, mid + 1, t, p->right);
			}
		}

		Tp get(node *p, int pos, int s, int t) {
			if (s == t) {
				return p->value;
			} else {
				int mid = (s + t) >> 1;
				if (pos <= mid) {
					return get(p->left, pos, s, mid);
				} else {
					return get(p->right, pos, mid + 1, t);
				}
			}
		}

		void modify(node *&p, int pos, int s, int t, Tp val) {
			node tmp = *p;
			p = new node();
			*p = tmp;

			if (s == t) {
				p->value = val;
			} else {
				int mid = (s + t) >> 1;
				if (pos <= mid) {
					modify(p->left, pos, s, mid, val);
				} else {
					modify(p->right, pos, mid + 1, t, val);
				}
			}
		}

	public:
		presidentTree() {}

		void operator=(const auto &a) {
			build(a, 1, Nb, roots[0]);
		}

		Tp get(int v, int pos) {
			roots.push_back(roots[v]);
			return get(roots.back(), pos, 1, Nb);
		}

		void set(int v, int pos, Tp val) {
			roots.push_back(roots[v]);
			modify(roots.back(), pos, 1, Nb, val);
		}
};
presidentTree<int, 1000005> box;
array<int, 1000005> a;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cin >> n >> m;
	for (int i = 1; i <= n; ++i) {
		cin >> a[i];
	}

	box = a;

	for (int _ = 1; _ <= m; ++_) {
		int v, op, loc, value;
		cin >> v >> op >> loc;
		if (op == 1) {
			cin >> value;
			box.set(v, loc, value);
		} else {
			cout << box.get(v, loc) << "\n";
//			cout.flush();
		}
	}
	return 0;
}
原文