跳到正文

休闲·娱乐

!?可持久化数据结构竟可以O(1)操作?!

Gary0约 5 分钟
原文

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

文章信息与版本

文章信息

发布
2026年10月15日
收录
2026年10月15日
更新
2026年11月18日
篇幅
约 5 分钟

版本

  1. v4当前
  2. v3
  3. v2
  4. v1

我们依据可持久化数组进行一些修改,得到这个支持 O(1)\mathcal{O}(1) 修改与查询的可持久化数字。

实现使用可持久化数组不稍地作删减即可:

C++
int rt[200005];
struct tree
{
	int tl;
	struct node { int p, x; } tr[200005];
	int set(int u, int x) { tr[++tl] = { u, x }; return tl; }
	int query(int u) { return tr[u].x; }
	int prnt(int u) { return tr[u].p; }
};

以上的实现不仅支持了正常的可持久化数组所支持的单点修改、单点查询,还支持了额外的回退到上一个历史版本的操作,而且所有操作都是 O(1)\mathcal{O}(1) 的。

可以发现这种数据结构具有复杂度优秀、常数小、实现简单等优势,但可拓展性差的缺点也并不略地显突出。

显然,这种数据结构用途十分不广泛,可以用于记录部分滚动数组优化的 dp 的转移路径。

例如求最长上升子序列并输出方案:

C++
// Copyright 2026 (C) Gary0
// All rights reserved
#define debug
#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
typedef long long LL;
using namespace std;

int n;
int a[200005], dp[200005];

int rt[200005];
struct tree
{
	int tl;
	struct node { int p, x; } tr[200005];
	int set(int u, int x) { tr[++tl] = { u, x }; return tl; }
	int query(int u) { return tr[u].x; }
	int prnt(int u) { return tr[u].p; }
} tr;

int main()
{
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	memset(dp, 0x3f, sizeof(dp));
	cin >> n;
	for (int i = 1; i <= n; i++) cin >> a[i];
	dp[0] = 0, rt[0] = tr.set(0, 0);
	for (int i = 1; i <= n; i++)
	{
		int p = lower_bound(dp, dp + n + 1, a[i]) - dp;
		dp[p] = a[i], rt[p] = tr.set(rt[p - 1], i);
	}
	int mx = 0;
	while (dp[mx + 1] < inf) mx++;
	int u = rt[mx];
	vector<int> ans;
	while (tr.query(u)) ans.push_back(tr.query(u)), u = tr.prnt(u);
	cout << ans.size() << "\n";
	while (!ans.empty()) cout << a[ans.back()] << " ", ans.pop_back();
	return 0;
}

但是肉眼可见,上述的实现还是太冗长而猎奇了,所以我们精简并好好写一下,得到以下版本:

C++
// Copyright 2026 (C) Gary0
// All rights reserved
#define debug
#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
typedef long long LL;
using namespace std;

int n;
int a[200005], rt[200005], dp[200005];
vector<pair<int, int>> v;

int main()
{
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	memset(dp, 0x3f, sizeof(dp));
	cin >> n;
	for (int i = 1; i <= n; i++) cin >> a[i];
	dp[0] = 0, v.push_back({ 0, 0 });
	for (int i = 1; i <= n; i++)
	{
		int p = lower_bound(dp, dp + n + 1, a[i]) - dp;
		dp[p] = a[i], rt[p] = v.size(), v.push_back({ rt[p - 1], i });
	}
	int mx = 0;
	while (dp[mx + 1] < inf) mx++;
	int u = rt[mx];
	vector<int> ans;
	while (u) ans.push_back(v[u].second), u = v[u].first;
	cout << ans.size() << "\n";
	while (!ans.empty()) cout << a[ans.back()] << " ", ans.pop_back();
	return 0;
}

把 O(1)\mathcal{O}(1) 可持久化发扬光大,让 O(log⁡n)\mathcal{O}(\log n) 可持久化成为时代的眼泪!