跳到正文

题解

P4081 题解

creation_hy约 5 分钟
原文
文章信息与版本

文章信息

发布
2022年12月29日
收录
2026年5月7日
更新
2026年11月10日
篇幅
约 5 分钟
题目
P4081

版本

  1. v2当前
  2. v1

广义 SAM 板子题。

思路

首先对所有串建广义 SAM。

本题和模版唯一不同的一点就是,模版是统计总共有多少子串,多个相同串虽然不算,但是起码算一个,而这题是一个都不算。。。

考虑在 parent 树上染色。

做法:

  • 建广义 SAM。

  • 对于每个字符串,往上跳 father 指针。

    如果 parent 树当前节点已经染过其他颜色了,因为多个相同串一个都不算,那么就把它设为不可用。

    否则,将该节点染色为当前字符串编号。

最后统计答案的时候,直接按照染上的颜色统计即可。

如果当前颜色不可用,那就不管。否则把对应颜色的答案加上子串数量。

如果你不知道怎么求子串数量,说明你根本不会用 SAM,请参考 P2408 和 P6139。

还是很简单的。

具体实现(update 即染色函数):

C++
inline void update(int x, int id)
{
    while (~x && ~num[x] && num[x] != id)
    {
        num[x] = num[x] ? -1 : id;
        x = fa[x];
    }
}
inline void solve()
{
    int p = 0;
    for (int i = 1; i <= n; i++, p = 0)
        for (char c : s[i])
            update(p = t[p][c - 'a'], i);
    for (int i = 0; i <= tot; i++)
        if (~num[i] && ~fa[i])
            ans[num[i]] += len[i] - len[fa[i]];
    for (int i = 1; i <= n; i++)
        cout << ans[i] << '\n';
}

代码:

C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5 + 5;
string s[N];
int n;
struct SAM
{
    int tot, last, fa[N << 1], len[N << 1], t[N << 1][26];
    int num[N << 1], ans[N << 1];
    inline SAM()
    {
        tot = last = 0;
        fa[0] = -1;
    }
    inline void insert(char c)
    {
        c -= 'a';
        int cur = ++tot;
        len[cur] = len[last] + 1;
        int p = last;
        last = cur;
        while (~p && !t[p][c])
            t[p][c] = cur, p = fa[p];
        if (!~p)
        {
            fa[cur] = 0;
            return;
        }
        int x = t[p][c];
        if (len[p] + 1 == len[x])
            fa[cur] = x;
        else
        {
            len[++tot] = len[p] + 1;
            fa[tot] = fa[x];
            memcpy(t[tot], t[x], sizeof(t[x]));
            while (~p && t[p][c] == x)
                t[p][c] = tot, p = fa[p];
            fa[x] = fa[cur] = tot;
        }
    }
    inline void update(int x, int id)
    {
        while (~x && ~num[x] && num[x] != id)
        {
            num[x] = num[x] ? -1 : id;
            x = fa[x];
        }
    }
    inline void solve()
    {
        int p = 0;
        for (int i = 1; i <= n; i++, p = 0)
            for (char c : s[i])
                update(p = t[p][c - 'a'], i);
        for (int i = 0; i <= tot; i++)
            if (~num[i] && ~fa[i])
                ans[num[i]] += len[i] - len[fa[i]];
        for (int i = 1; i <= n; i++)
            cout << ans[i] << '\n';
    }
} sam;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        cin >> s[i];
        sam.last = 0;
        for (char c : s[i])
            sam.insert(c);
    }
    sam.solve();
    return 0;
}
原文
存档评论6 条抓取于