跳到正文

题解

完美字符串 题解

QiyuTong约 16 分钟
原文

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

文章信息与版本

文章信息

收录
2026年1月30日
更新
2026年4月14日
篇幅
约 16 分钟

版本

  1. v2当前
  2. v1

题面看这里:https://www.luogu.com.cn/problem/T726583

前情提要

验题人题解。

不保证做法最优。但是已经挺人类智慧的了。

题解里的 O(n)O(n) 是在字符集大小看作常数的情况下。注:但即使不看作常数 ∣Σ∣×∑∣Wi∣∼3e7|\Sigma| \times \sum |W_i| \sim 3e7 相较于 ∣S∣∼1e7 |S| \sim 1e7 也可看做线性。

∼O(nn)\sim O(n\sqrt{n}) 做法

先把所有模式串的 AC 自动机建出来。

核心思路:答案可以看作是一段区间内的完整匹配的前缀和,可以转化成结束在区间内匹配减去在左端点“匹配到一半”的权值和。这样前者可以用前缀和维护(我们叫它 bb 数组),后者可以差分维护(我们叫它 aa 数组)。

那么,我们只要从前往后跑 AC 自动机,每有一个匹配 [l,r][l,r] 就在 [l,r−1][l,r-1] 加上其权值,维护匹配到一半的的权值和数组 AA;再在 rr 处加上权值,维护以 rr 为结尾的权值和数组 BB。

AA 用差分维护,最后前缀和一下变成 aa 数组;BB 明显可以预处理时,沿 fail 树从祖先往孩子传递权值后 O(n)O(n) 做好,和 trie 图一起做,再做前缀和变成 bb 数组。

区间 [l,r][l,r] 答案变为 b[r]−b[l−1]−a[l]b[r] - b[l - 1] - a[l],可以分离变量 O(n)O(n) 维护最大值。

该做法的理论复杂度为 O(P+∣S∣)O(P + |S|),其中 PP 为匹配次数,理论最大约 O(∣S∣⋅∑∣Wi∣)O(|S| \cdot \sum |W_i|) 量级,发现加权值的操作只跟长度有关可优化,将同一长度模式串的操作合并,复杂度降至 O(∣S∣⋅∑∣Wi∣)O(|S| \cdot \sqrt{\sum |W_i|})。

于是总复杂度为 O(∣S∣⋅∑∣Wi∣)O(|S| \cdot \sqrt{\sum |W_i|}),空间复杂度 ∼O(∣Σ∣⋅∣S∣)\sim O(|\Sigma| \cdot |S|)。

具体算法:

  1. 构建 WW 的 AC 自动机。
  2. 构建 bb。
    1. 传递所有后缀的权值。
    2. 跑一遍 SS,每次加上当前状态的权值。
  3. 对于每个模式串长度 ll,执行以下步骤:
    1. 清空 AC 自动机权值后,只传递所有该长度的权值。
    2. 拿现在的 AC 自动机跑一遍 SS,每次在 [r−l+2,r−1][r-l+2,r-1] 区间加上当前的权值。 差分维护,O(∣S∣)O(|S|)。
  4. 把差分数组转化成原数组 O(∣S∣)O(|S|),把 bb 转化为前缀和。
  5. 对于每个 rr,找到使分离变量部分的前缀最小 ll 与其匹配,维护答案最小。可以在枚举 rr 的时候维护关于 ll 的部分的最小值,然后维护当前值减去最小值的最大值,可以让这部分达到线性。

这是出题组一开始的想法。大部分人在这里就放弃了。当然能想到这里,说明你对 AC 自动机已经有了相当的了解,值得肯定。预期得分 6060 ~ 9595 分,不排除卡过的可能性。

∼O(n)\sim O(n) 做法

但为了女朋友开心还是要争一下。

我们发现,维护 aa 数组的关键的难点在于,结束在某个位置的所有匹配,其长度可能是不同的,导致开始位置不同,那么要加权值的区间也不同。

考虑避开这一点。

抛开字符串题目的表象,这是一个很容易的思路:我们把“给区间 [l,r−1][l,r-1] 加上 ww”转化为“给区间 [l,+∞)[l,+\infty) 加上 ww,同时给区间 [r,+∞)[r,+\infty) 加上 −w-w”。

那有人就要问了:你 AC 自动机匹配到的不是 rr 吗?你想要根据模式串长度算出 ll,不久又退回到 O(n⋅n)O(n\cdot\sqrt{n}) 做法了嘛?

我给你一行字的思考时间。

是的,AC 自动机就是匹配 rr,那么,我们把 AC 自动机反过来,把文本串也反过来,那么效果不久跟匹配 ll 一样了吗?这就是我们前面分离变量的作用,现在我们可以分别对 ll 和 rr 的效果进行计算。

更形式化地,我们有以下结论。

令 m[i]m[i] 为在下标 ii 开始的匹配的权值之和,n[i]n[i] 为在下标 ii 结束的匹配权值之和。

则对于 i=0i=0 有 a[i]=m[i]−n[i]a[i]=m[i]-n[i],否则 a[i]=m[i]−n[i]+a[i−1](i>0)a[i]=m[i]-n[i]+a[i-1](i>0)。

而 n[i]n[i] 可以通过传递权值后在正文本串上跑正模式串维护, m[i]m[i] 可以通过传递权值后在反文本串上跑反模式串维护。

注意到 nn 的前缀和为 bb。对于区间 [l,r][l,r],我们的答案为依然 b[r]−b[l−1]−a[l]b[r]-b[l-1]-a[l],但此时可以 O(∣S∣)O(|S|) 计算。

到此,加上个快读快写,就结束了。该算法时间和空间复杂度 O(∣S∣+Σ⋅∑∣Wi∣)O(|S|+\Sigma\cdot\sum|W_i|), 预期得分 100100 分。

注意实现细节,做多余的操作(比如我一开始多建了个 fail 树)可能会导致在第 8、9 个点 TLE。

std 代码

C++
/*
T726583 Perfect String
Author: Irade
Date: 1/30/2026
Time Complexity: O(|S| + |\Sigma| \times \Sigma W)
Space Complexity: O(|\Sigma| \times W)
*/
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr int BET = 26; // 字符集大小

// 快读快写板子
struct FastIO {
    static constexpr int BUFSIZE = 1 << 20;
    char ibuf[BUFSIZE], obuf[BUFSIZE];
    char *ip = ibuf, *iend = ibuf;
    char *op = obuf, *oend = obuf + BUFSIZE;
    
    FastIO() {
        ibuf[0] = obuf[0] = 0;
    }
    
    ~FastIO() {
        flush();
    }
    
    char getchar() {
        if (ip == iend) {
            iend = ibuf + fread(ibuf, 1, BUFSIZE, stdin);
            ip = ibuf;
            if (ip == iend) return EOF;
        }
        return *ip++;
    }
    
    template<typename T>
    void read(T& x) {
        x = 0;
        bool neg = false;
        char c = getchar();
        while (c < '0' || c > '9') {
            if (c == '-') neg = true;
            c = getchar();
        }
        while (c >= '0' && c <= '9') {
            x = x * 10 + (c - '0');
            c = getchar();
        }
        if (neg) x = -x;
    }
    
    void read(char* s) {
        char c = getchar();
        while (c <= ' ') c = getchar();
        while (c > ' ') *s++ = c, c = getchar();
        *s = '\0';
    }
    
    void read(string& s) {
        s.clear();
        char c = getchar();
        while (c <= ' ') c = getchar();
        while (c > ' ') s.push_back(c), c = getchar();
    }
    
    void putchar(char c) {
        if (op == oend) {
            fwrite(obuf, 1, op - obuf, stdout);
            op = obuf;
        }
        *op++ = c;
    }
    
    template<typename T>
    void write(T x) {
        if (x < 0) {
            putchar('-');
            x = -x;
        }
        if (x > 9) write(x / 10);
        putchar(x % 10 + '0');
    }
    
    void write(const char* s) {
        while (*s) putchar(*s++);
    }
    
    void write(const string& s) {
        for (char c : s) putchar(c);
    }
    
    void flush() {
        if (op != obuf) {
            fwrite(obuf, 1, op - obuf, stdout);
            op = obuf;
        }
    }
} io;

class AC { // AC 自动机板子,这里最好用 class 或者 struct,因为要开两个
    struct Node {
        int next[BET];
        int fail;
        ll weight;
        Node() {
            memset(next, -1, sizeof(next));
            fail = -1;
            weight = 0;
        }
    };
    vector<Node> nodes;
    
public:
    AC() {
        nodes.clear();
        nodes.emplace_back();
    }
    
    void insert(const string& s, ll w) {
        int u = 0;
        for (char _c : s) {
            const int c = _c - 'a';
            if (nodes[u].next[c] == -1) {
                nodes[u].next[c] = nodes.size();
                nodes.emplace_back();
            }
            u = nodes[u].next[c];
        }
        nodes[u].weight += w;
    }
    
    void build() {
        queue<int> q;
        for (int i = 0; i < BET; ++i) {
            if (nodes[0].next[i] != -1) {
                nodes[nodes[0].next[i]].fail = 0;
                q.push(nodes[0].next[i]);
            } else {
                nodes[0].next[i] = 0;
            }
        }
        
        while (!q.empty()) {
            const int u = q.front();
            q.pop();
            
            nodes[u].weight += nodes[nodes[u].fail].weight; // 沿 fail 链传递权值,很重要!
            
            for (int i = 0; i < BET; ++i) { // 预处理出 trie 图提升常数
                int v = nodes[u].next[i];
                if (v != -1) {
                    nodes[v].fail = (nodes[u].fail == -1) ? 0 : nodes[nodes[u].fail].next[i];
                    q.push(v);
                } else {
                    nodes[u].next[i] = (nodes[u].fail == -1) ? 0 : nodes[nodes[u].fail].next[i];
                }
            }
        }
    }
    
    vector<ll> query(const string& s) {
        const int n = s.size();
        vector<ll> res;
        res.reserve(n);
        
        int u = 0;
        for (char c : s) {
            u = nodes[u].next[c - 'a'];
            res.push_back(nodes[u].weight);  // 直接 push_back 即可,因为该状态对应的就是我们已经传递好的权值
        }
        return res;
    }
};

int main() {
    string text;
    io.read(text);
    int n = text.size();
    
    int m;
    io.read(m);
    
    AC oAC, rAC;
    for (int i = 0; i < m; ++i) {
        string pattern;
        ll w;
        io.read(pattern);
        io.read(w);
        oAC.insert(pattern, w);
        reverse(pattern.begin(), pattern.end()); // 同时构建两个 AC 自动机,不用存储匹配
        rAC.insert(pattern, w);
    }
    
    oAC.build();
    rAC.build(); // 建立 fail 树,传递权值
    
    // 查询结果
    vector<ll> oWeight = oAC.query(text); // 这个是 n[i]
    vector<ll> rWeight = rAC.query(text); // 这个是 m[i]
    reverse(rWeight.begin(), rWeight.end()); // 注意,我们是在反串上跑的,要反转一下
    
    // 计算答案
    /* min_prefix 存储前缀最小值
      current_sum 存储 b[i],即结束在下标 i 之前的所有匹配的权值和
      max_gain 存储当前答案
      prefix_sum 存储 a[i],到下标 i 时匹配到一半的模式串的权值和
    */
    ll current_sum = 0, min_prefix = 0, max_gain = LLONG_MIN; 
    ll prefix_sum = 0;
    
    for (int i = 0; i < n; ++i) {
        current_sum += rWeight[i] - oWeight[i]; // 我们的公式:a[i] = m[i] - n[i]
        prefix_sum += oWeight[i]; // n[i] 的前缀和是 b[i]
        
        // 更新最大增益
        max_gain = max(max_gain, prefix_sum - min_prefix);

        // 更新最小前缀
        min_prefix = min(min_prefix, current_sum + prefix_sum); // 注意要先更新增益再更新前缀,否则会计入空串
    }
    
    io.write(max_gain);
    io.putchar('\n');
    
    return 0;
}

重要提示

但是你可不能说她的作文一段优美的都没有——她会生气,然后给你扣分的!

如果你只在第 6 个点 WA 了,那么再次提醒:不能计入空串!

如果你只在第 10 个点 TLE 了,可能是你的算法时间复杂度跟匹配次数是相关的。请检查你的算法。