P12538 [XJTUPC 2025] 泰拉构史 题解

· · 题解

由于序列中的元素互不相同,一个数最多能和两个数交换,那么我们只需要关心当前序列的最后两个位置。

那么有 DP:f_{i, x, y} 表示考虑了 a_{1 \sim i},构成的序列最后两个元素为 x, y 的方案数。每次在最后加入一个数时尝试往前换来转移。

显然对于一个 i,合法的 (x, y) 只有 O(1) 种,那么直接用 map 存状态即可做到 O(n)。

#include <algorithm>
#include <cstring>
#include <utility>
#include <cstdio>
#include <vector>
#include <map>
#define mkp make_pair
#define fi first
#define se second
#define mod 998244353
using namespace std;
typedef pair<int, int> pii;
const int N = 1000005;
int n, a[N], ans;map<pii, int> f[N];
inline void add(int& x, int y){x += y;if (x >= mod) x -= mod;}
inline int ok(int x, int y){return x - y == 1 || y - x == 1;}
int main(){scanf("%d", &n);
    for (int i = 1;i <= n;i ++) scanf("%d", &a[i]);
    f[0][mkp(-1, -1)] = 1;
    for (int i = 1;i <= n;i ++)
    for (auto [pi, v] : f[i - 1]){auto [x, y] = pi;
        add(f[i][mkp(y, a[i])], v);
        if (ok(a[i], y)){add(f[i][mkp(a[i], y)], v);
        if (ok(a[i], x)) add(f[i][pi], v);}
    }
    for (auto [pi, v] : f[n]) add(ans, v);printf("%d", ans);
}