跳到正文

题解

一篇 PAM 的题解

jlhj约 5 分钟
原文

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

文章信息与版本

文章信息

发布
2026年8月7日
收录
2026年8月7日
更新
2026年11月21日
篇幅
约 5 分钟
获赞
4
题目
P15696

版本

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

前置知识

  • 回文自动机 PAM

介绍详见 OI Wiki 中的描述,此处不作赘述。

思路分析

分两种情况讨论:

  • 当前字符是小写字母时,按照题意插入此字符,然后统计。
  • 当前字符是 - 时,删除字符串末尾的字符,然后统计。

构建回文自动机,按照题意模拟即可。

删除操作

由于 PAM 结点只增不减(保证 fail 指针有效及结点复用),删除时采用状态回滚策略,通过维护历史栈恢复上一状态。

空间

PAM 结点数最多为 ∣S∣+2|S| + 2,Q≤10000Q \le 10000,数组开 N = 10010 足够。

代码实现

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long // 十年 OI 一场空,不开 long long 见祖宗
const int N = 10010;
const int AL = 26;
struct PAM {
    int n, last, tot;
    int tp; // 回文子串总数
    int len[N], fail[N];
    int num[N];         // num[last]: 以当前位置结尾的回文子串个数
    int nextt[N][AL];
    vector<int> lh;     // last 历史栈 (用于回滚)
    vector<int> th;     // 答案 tp 历史栈 (用于回滚)
    vector<int> ch;     // 字符栈
    int s[N];
    PAM() {
        init();
    }
    void init() {
        n = 0; last = 0; tot = 2; tp = 0;
        len[0] = 0; fail[0] = 1;
        len[1] = -1; fail[1] = 1;
        num[0] = num[1] = 0;
        s[0] = -1; // 哨兵:防止 get_fail 匹配时越界
        memset(nextt, 0, sizeof(nextt));
        lh.clear(); th.clear(); ch.clear();
        lh.push_back(last);
        th.push_back(tp);
    }
    int get_fail(int x) {
        while (s[n - len[x] - 1] != s[n]) {
            x = fail[x];
        }
        return x;
    }
    void add(int c) {
        s[++n] = c;
        int cur = get_fail(last);
        if (!nextt[cur][c]) {
            int now = tot++;
            len[now] = len[cur] + 2;
            fail[now] = (len[now] == 1) ? 0 : nextt[get_fail(fail[cur])][c];
            nextt[cur][c] = now;
            num[now] = num[fail[now]] + 1; // 核心:统计回文后缀数
        }
        last = nextt[cur][c];
        tp += num[last]; // 累加新增贡献
        // 存档
        ch.push_back(c);
        lh.push_back(last);
        th.push_back(tp);
    }
    void remove() {
        if (n == 0) {
            return;
        }
        ch.pop_back();
        lh.pop_back(); // 回滚 last
        th.pop_back(); // 回滚答案
        last = lh.back();
        tp = th.back();
        n--;
    }
    int get_total() {
        return tp;
    }
};
PAM p;
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    int q;
    cin >> q;
    while (q--) {
        char op;
        cin >> op;
        if (op != '-') {
            p.add(op - 'a');
        }
        else {
            p.remove();
        }
        cout << p.get_total() << ' ';
    }
    return 0;
}

复杂度分析

  • 时间复杂度:O(Q)O(Q)。PAM 的 get_fail 跳转次数是均摊 O(1)O(1) 的,删除操作仅为栈操作 O(1)O(1),不存在真正意义上的 O(q2)O(q^2) 最坏情况。
  • 空间复杂度:O(Q)O(Q)。PAM 结点数最多为 Q+2Q+2,栈空间也为 O(Q)O(Q)。