可持久化数字

· · 休闲·娱乐

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

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

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; }
};

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

可以发现这种数据结构具有复杂度优秀、常数小、实现简单等优势。

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

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

// Copyright 6202 (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;
}

但是肉眼可见,上述的实现还是太冗长而诡异了,精简一下,得到以下版本:

// Copyright 6202 (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;
}

该数据结构的传奇还不止如此,它的博大之处在于,只要修改几个字符就可以得到新的数据结构:

int rt[200005];
struct stk
{
    int tl;
    struct node { int p, x; } tr[200005];
    int push(int u, int x) { tr[++tl] = { u, x }; return tl; }
    int top(int u) { return tr[u].x; }
    int pop(int u) { return tr[u].p; }
};

可持久化栈!

只要把可持久化数字的代码修改几个函数名就可以得到可持久化栈,简直人道。