Olympiad in Informatics

Suffix Automaton | SAM

Overview

The suffix automaton is a powerful tool for handling string information. A suffix automaton is stored on a trie, and together with the Link pointers it can be regarded as a DAG. Any path starting from the origin can be regarded as a substring of the string, and no duplicate substring information exists on a suffix automaton (however, we can make some extensions to maintain substring position information).

Constructing the SAM

namespace SAM
{

struct node
{
    int dep, link, ch[26], pos;
} nodes[MAX_N << 1];

int ptot = 1, last_ptr = 1;

void insert(int c, int idx)
{
    int pre = last_ptr, p = last_ptr = ++ptot;
    nodes[p].dep = nodes[pre].dep + 1, nodes[p].pos = idx;
    while (pre && nodes[pre].ch[c] == 0)
        nodes[pre].ch[c] = p, pre = nodes[pre].link;
    if (pre == 0)
        nodes[p].link = 1;
    else
    {
        int q = nodes[pre].ch[c];
        if (nodes[q].dep == nodes[pre].dep + 1)
            nodes[p].link = q;
        else
        {
            int clone = ++ptot;
            nodes[clone] = nodes[q], nodes[clone].dep = nodes[pre].dep + 1;
            nodes[p].link = nodes[q].link = clone;
            while (pre && nodes[pre].ch[c] == q)
                nodes[pre].ch[c] = clone, pre = nodes[pre].link;
        }
    }
}

} // namespace SAM

Constructing the SAM takes linear time, and characters can be added dynamically.

Below I introduce how to construct a generalized suffix automaton. This is the offline approach:

// P6139.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 2e6 + 200;

int n, pos[MAX_N];
char str[MAX_N];

namespace Trie
{

    int ch[MAX_N][26], ptot = 1, up[MAX_N], depot[MAX_N];

    void insert()
    {
        int p = 1;
        for (int i = 1; str[i]; i++)
        {
            if (ch[p][str[i] - 'a'] == 0)
                ch[p][str[i] - 'a'] = ++ptot, up[ptot] = p, depot[ptot] = str[i] - 'a';
            p = ch[p][str[i] - 'a'];
        }
    }

} // namespace Trie

namespace SAM
{

    struct node
    {
        int ch[26], link, dep;
    } nodes[MAX_N];

    int ptot = 1, last_ptr = 1;

    void insert(int c)
    {
        int pre = last_ptr, p = last_ptr = ++ptot;
        nodes[p].dep = nodes[pre].dep + 1;
        while (pre && nodes[pre].ch[c] == 0)
            nodes[pre].ch[c] = p, pre = nodes[pre].link;
        if (pre == 0)
            nodes[p].link = 1;
        else
        {
            int q = nodes[pre].ch[c];
            if (nodes[q].dep == nodes[pre].dep + 1)
                nodes[p].link = q;
            else
            {
                int clone = ++ptot;
                nodes[clone] = nodes[q], nodes[clone].dep = nodes[pre].dep + 1;
                nodes[p].link = nodes[q].link = clone;
                while (pre && nodes[pre].ch[c] == q)
                    nodes[pre].ch[c] = clone, pre = nodes[pre].link;
            }
        }
    }

} // namespace SAM

int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%s", str + 1), Trie::insert();
    queue<int> q;
    for (int i = 0; i < 26; i++)
        if (Trie::ch[1][i])
            q.push(Trie::ch[1][i]);
    pos[1] = 1;
    while (!q.empty())
    {
        int u = q.front();
        q.pop();
        SAM::last_ptr = pos[Trie::up[u]];
        SAM::insert(Trie::depot[u]);
        pos[u] = SAM::last_ptr;
        for (int i = 0; i < 26; i++)
            if (Trie::ch[u][i])
                q.push(Trie::ch[u][i]);
    }
    long long ans = 0;
    for (int i = 2; i <= SAM::ptot; i++)
        ans += SAM::nodes[i].dep - SAM::nodes[SAM::nodes[i].link].dep;
    printf("%lld\n", ans);
    return 0;
}

The online approach:

// CF316G3.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 1e6 + 200;

int n, lens[11], li[11], ri[11];
char str[11][MAX_N];

// SAM;

struct node
{
    int ch[26], dep, link;
} nodes[MAX_N];

int ptot = 1, last_ptr = 1, siz[11][MAX_N], rnk[MAX_N], bucket[MAX_N];
vector<int> G[MAX_N];

void insert(int c)
{
    int pre = last_ptr;
    if (nodes[pre].ch[c] != 0)
    {
        int q = nodes[pre].ch[c];
        if (nodes[q].dep == nodes[pre].dep + 1)
            last_ptr = q;
        else
        {
            int clone = ++ptot;
            nodes[clone] = nodes[q], nodes[clone].dep = nodes[pre].dep + 1;
            last_ptr = clone, nodes[q].link = clone;
            while (pre && nodes[pre].ch[c] == q)
                nodes[pre].ch[c] = clone, pre = nodes[pre].link;
        }
    }
    else
    {
        int p = last_ptr = ++ptot;
        nodes[p].dep = nodes[pre].dep + 1;
        while (pre && nodes[pre].ch[c] == 0)
            nodes[pre].ch[c] = p, pre = nodes[pre].link;
        if (pre == 0)
            nodes[p].link = 1;
        else
        {
            int q = nodes[pre].ch[c];
            if (nodes[q].dep == nodes[pre].dep + 1)
                nodes[p].link = q;
            else
            {
                int clone = ++ptot;
                nodes[clone] = nodes[q], nodes[clone].dep = nodes[pre].dep + 1;
                nodes[p].link = nodes[q].link = clone;
                while (pre && nodes[pre].ch[c] == q)
                    nodes[pre].ch[c] = clone, pre = nodes[pre].link;
            }
        }
    }
}

int main()
{
    scanf("%s%d", str[0] + 1, &n), lens[0] = strlen(str[0] + 1);
    for (int i = 1; str[0][i]; i++)
        insert(str[0][i] - 'a'), siz[0][last_ptr]++;
    for (int i = 1; i <= n; i++)
    {
        scanf("%s%d%d", str[i] + 1, &li[i], &ri[i]), lens[i] = strlen(str[i] + 1);
        last_ptr = 1;
        for (int j = 1; str[i][j]; j++)
            insert(str[i][j] - 'a'), siz[i][last_ptr]++;
    }
    for (int i = 1; i <= ptot; i++)
        bucket[nodes[i].dep]++;
    for (int i = 1; i <= ptot; i++)
        bucket[i] += bucket[i - 1];
    for (int i = 1; i <= ptot; i++)
        rnk[bucket[nodes[i].dep]--] = i;
    for (int i = ptot; i >= 2; i--)
        for (int j = 0; j <= n; j++)
            siz[j][nodes[rnk[i]].link] += siz[j][rnk[i]];
    long long ans = 0;
    for (int i = 2; i <= ptot; i++)
        if (siz[0][i])
        {
            bool flag = true;
            for (int j = 1; j <= n; j++)
                flag &= li[j] <= siz[j][i] && siz[j][i] <= ri[j];
            if (flag)
                ans += nodes[i].dep - nodes[nodes[i].link].dep;
        }
    printf("%lld\n", ans);
    return 0;
}

The Link Tree

The Link tree is a really neat thing: it organizes a number of Endpos equivalence classes into a tree structure. It has the following properties:

  • \(dep[u] = dep[fa] + 1\), because they represent sharing the same suffix, but can keep splitting (the prefixes differ, but there exist smaller yet deeper Endpos equivalence classes).
  • \(endpos[u] \subset endpos[fa]\); using this property, we can apply segment tree merging, the standard trick, to maintain the concrete equivalence classes.

Applications of the SAM

Counting distinct substrings

Notice that the representation of a substring in the SAM is unique and unaffected by position (that is, nothing gets counted twice), and every path starting from the root is a unique substring, so to solve this problem we just count the paths in the DAG.


Counting the occurrences of a string in the main string

We let the string walk through the main string's SAM to node \(p\), and then recall what we know about Endpos equivalence classes: such paths correspond one-to-one with the main string, so we only need to use the properties of \(p\) to count, and clearly the answer is the size of \(endpos[p]\). After placing the marks early in the construction, we just run one DFS following the tree structure to get the sizes.


Finding the LCP of two strings

Build a SAM for one of the strings, then just jump upward by brute force. Concretely, jumping upward by brute force works just like in an Aho–Corasick automaton, but you need to pay attention to the string length: every jump up to the Link parent means giving up a prefix of some length, and this is where it differs from the Aho–Corasick automaton.


CF1120C Compress String

This problem is clearly an \(O(n^2)\) DP. Let the state \(f_i\) be the optimal cost up to position \(i\). The transition is very obvious:

\[ f_i = \min \begin{cases} f_{i - 1} + A \\ f_j + b, \text{if } S[j + 1 \dots i] \subset S[1 \dots j] \end{cases} \]

Precompute the earliest node \(pos[i][j]\) of each substring and the earliest occurrence position of every node, and then just check.

// CF1120C.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 1e5 + 200;

struct node
{
    int ch[26], link, dep, occur = 0x3f3f3f3f;
} nodes[MAX_N];

int n, ca, cb, ptot, last_cur, bucketA[MAX_N], bucketB[MAX_N];
int pos[5001][5001], dp[MAX_N];
char str[MAX_N];

void sam_initialize() { last_cur = ++ptot; }

void insert(int c, int pos)
{
    int cur = ++ptot;
    nodes[cur].dep = nodes[last_cur].dep + 1;
    nodes[cur].occur = pos;
    int p = last_cur;
    while (p && nodes[p].ch[c] == 0)
        nodes[p].ch[c] = cur, p = nodes[p].link;

    if (p == 0)
        nodes[cur].link = 1;
    else
    {
        int q = nodes[p].ch[c];

        if (nodes[p].dep + 1 == nodes[q].dep)
            nodes[cur].link = q;
        else
        {
            int clone = ++ptot;
            nodes[clone].dep = nodes[p].dep + 1;
            memcpy(nodes[clone].ch, nodes[q].ch, sizeof(nodes[q].ch));
            nodes[clone].link = nodes[q].link;
            while (p && nodes[p].ch[c] == q)
                nodes[p].ch[c] = clone, p = nodes[p].link;
            nodes[q].link = nodes[cur].link = clone;
        }
    }

    last_cur = cur;
}

void stringSort()
{
    for (int i = 1; i <= ptot; i++)
        bucketA[i] = 0;
    for (int i = 1; i <= ptot; i++)
        bucketA[nodes[i].dep]++;
    for (int i = 1; i <= ptot; i++)
        bucketA[i] += bucketA[i - 1];
    for (int i = 1; i <= ptot; i++)
        bucketB[bucketA[nodes[i].dep]--] = i;

    for (int i = ptot; i >= 1; i--)
        nodes[nodes[bucketB[i]].link].occur = min(nodes[nodes[bucketB[i]].link].occur, nodes[bucketB[i]].occur);
}

int main()
{
    sam_initialize();
    scanf("%d%d%d%s", &n, &ca, &cb, str + 1);
    for (int i = 1; i <= n; i++)
        insert(str[i] - 'a', i);
    for (int i = 1; i <= n; i++)
    {
        int p = 1;
        for (int j = i; j <= n; j++)
        {
            p = nodes[p].ch[str[j] - 'a'];
            pos[i][j] = p;
        }
    }

    stringSort();
    for (int i = 1; i <= n; i++)
    {
        dp[i] = dp[i - 1] + ca;
        for (int j = 1; j <= i - 1; j++)
            if (nodes[pos[j + 1][i]].occur <= j)
            {
                dp[i] = min(dp[i], dp[j] + cb);
                break;
            }
    }
    printf("%d", dp[n]);
    return 0;
}

[SDOI2016] Generating Spells

This is really just the online version of counting distinct substrings. Let's consider what contribution a suffix makes to the answer: \(len(max\{endpos(p)\}) - len(\min\{endpos(p)\} + 1\), which is really just \(maxLen(p) - maxLen(fa[p])\).

// P4070.cpp
#include <bits/stdc++.h>
#define ll long long

using namespace std;

const int MAX_N = 1e6 + 200;

struct node
{
    map<int, int> ch;
    int link, len;
} nodes[MAX_N];

int n, ptot = 1, last_ptr = 1, opt;
ll ans;

void insert(int c)
{
    int pre = last_ptr, p = last_ptr = ++ptot;
    nodes[p].len = nodes[pre].len + 1;
    for (; pre != 0 && nodes[pre].ch[c] == 0; pre = nodes[pre].link)
        nodes[pre].ch[c] = p;
    if (pre == 0)
        nodes[p].link = 1;
    else
    {
        int q = nodes[pre].ch[c];
        if (nodes[q].len == nodes[pre].len + 1)
            nodes[p].link = q;
        else
        {
            int clone = ++ptot;
            nodes[clone] = nodes[q];
            nodes[clone].len = nodes[pre].len + 1;
            nodes[q].link = nodes[p].link = clone;
            for (; nodes[pre].ch[c] == q; pre = nodes[pre].link)
                nodes[pre].ch[c] = clone;
        }
    }
    ans += nodes[p].len - nodes[nodes[p].link].len;
}

int main()
{
    scanf("%d", &n);
    while (n--)
    {
        scanf("%d", &opt);
        insert(opt);
        printf("%lld\n", ans);
    }
    return 0;
}

[HEOI2016/TJOI2016] String

Restating the problem: over all substrings of the substring \(S[a..b]\), what is the maximum length of their longest common prefix with \(S[c..d]\)? Consider turning prefixes into suffixes (reverse the string), binary searching for each query, and pulling \(S[c..c+mid - 1]\) out and putting it into the SAM to check. Really, we only need to get the \(endpos\) equivalence class this string belongs to, and query whether the class has anything in the interval \([a, b]\) (remember to reverse it). Segment tree merging + SAM.

// P4094.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 2e5 + 200;

int n, q;
char str[MAX_N];

namespace SAM
{

struct node
{
    int link, dep, ch[26];
} nodes[MAX_N << 1];

int ptot = 1, last_ptr = 1;

void insert(int c)
{
    int pre = last_ptr, p = last_ptr = ++ptot;
    nodes[p].dep = nodes[pre].dep + 1;
    while (pre != 0 && nodes[pre].ch[c] == 0)
        nodes[pre].ch[c] = p, pre = nodes[pre].link;
    if (pre == 0)
        nodes[p].link = 1;
    else
    {
        int q = nodes[pre].ch[c];
        if (nodes[q].dep == nodes[pre].dep + 1)
            nodes[p].link = q;
        else
        {
            int clone = ++ptot;
            nodes[clone] = nodes[q], nodes[clone].dep = nodes[pre].dep + 1;
            nodes[q].link = nodes[p].link = clone;
            while (pre != 0 && nodes[pre].ch[c] == q)
                nodes[pre].ch[c] = clone, pre = nodes[pre].link;
        }
    }
}

} // namespace SAM

namespace SegmentTree
{

struct node
{
    int lson, rson, sum;
} nodes[MAX_N << 6];

int ptot;

void pushup(int p) { nodes[p].sum = nodes[nodes[p].lson].sum + nodes[nodes[p].rson].sum; }

int merge(int x, int y, int l, int r)
{
    if (x == 0)
        return y;
    if (y == 0)
        return x;
    if (l == r)
    {
        nodes[x].sum += nodes[y].sum;
        return x;
    }
    int mid = (l + r) >> 1, p = ++ptot;
    nodes[p].lson = merge(nodes[x].lson, nodes[y].lson, l, mid);
    nodes[p].rson = merge(nodes[x].rson, nodes[y].rson, mid + 1, r);
    pushup(p);
    return p;
}

int update(int qx, int l, int r, int p)
{
    if (p == 0)
        p = ++ptot;
    if (l == r)
    {
        nodes[p].sum++;
        return p;
    }
    int mid = (l + r) >> 1;
    if (qx <= mid)
        nodes[p].lson = update(qx, l, mid, nodes[p].lson);
    else
        nodes[p].rson = update(qx, mid + 1, r, nodes[p].rson);
    pushup(p);
    return p;
}

int query(int ql, int qr, int l, int r, int p)
{
    if (p == 0)
        return 0;
    if (ql <= l && r <= qr)
        return nodes[p].sum;
    int mid = (l + r) >> 1, ret = 0;
    if (ql <= mid)
        ret += query(ql, qr, l, mid, nodes[p].lson);
    if (mid < qr)
        ret += query(ql, qr, mid + 1, r, nodes[p].rson);
    return ret;
}

} // namespace SegmentTree

int roots[MAX_N << 1], pos[MAX_N], perm[MAX_N << 1], fa[21][MAX_N << 1], bucket[MAX_N << 1];

bool compare(const int &rhs1, const int &rhs2)
{
    return SAM::nodes[rhs1].dep < SAM::nodes[rhs2].dep;
}

bool check(int mid, int p, int l, int r)
{
    for (int i = 20; i >= 0; i--)
        if (SAM::nodes[fa[i][p]].dep >= mid && fa[i][p])
            p = fa[i][p];
    return SegmentTree::query(l + mid - 1, r, 1, n, roots[p]) > 0;
}

int main()
{
    scanf("%d%d%s", &n, &q, str + 1);
    reverse(str + 1, str + 1 + n);
    for (int i = 1; i <= n; i++)
    {
        SAM::insert(str[i] - 'a');
        roots[SAM::last_ptr] = SegmentTree::update(i, 1, n, roots[SAM::last_ptr]);
        pos[i] = SAM::last_ptr;
    }
    for (int i = 1; i <= SAM::ptot; i++)
        perm[i] = i;
    for (int i = 1; i <= SAM::ptot; i++)
        bucket[SAM::nodes[i].dep]++;
    for (int i = 1; i <= SAM::ptot; i++)
        bucket[i] += bucket[i - 1];
    for (int i = 1; i <= SAM::ptot; i++)
        perm[bucket[SAM::nodes[i].dep]--] = i;
    for (int i = SAM::ptot; i >= 1; i--)
        if (SAM::nodes[perm[i]].link != 0)
        {
            roots[SAM::nodes[perm[i]].link] =
                SegmentTree::merge(roots[SAM::nodes[perm[i]].link], roots[perm[i]], 1, n);
        }
    for (int i = 1; i <= SAM::ptot; i++)
        fa[0][i] = SAM::nodes[i].link;
    for (int i = 1; i <= 20; i++)
        for (int j = 1; j <= SAM::ptot; j++)
            fa[i][j] = fa[i - 1][fa[i - 1][j]];
    while (q--)
    {
        int a, b, c, d;
        scanf("%d%d%d%d", &a, &b, &c, &d);
        a = n - a + 1, b = n - b + 1;
        c = n - c + 1, d = n - d + 1;
        int l = 0, r = min(a - b + 1, c - d + 1), ret = 0;
        while (l <= r)
        {
            int mid = (l + r) >> 1;
            if (check(mid, pos[c], b, a))
                l = mid + 1, ret = mid;
            else
                r = mid - 1;
        }
        printf("%d\n", ret);
    }
    return 0;
}

CF700E Cool Slogans

This problem is pretty interesting. In the end we need a chain structure to represent what the problem describes, and we need to find the length of this chain. In fact, we can see that the nodes on this chain can be built directly from the nodes of the SAM. Suppose the string \(T\) is the root node; we find that every following node is contained in the node above it, and they all form a generated sub-chain of the \(link\) tree. This is very interesting, so we can DP directly on the Link tree: for each node, if the current “maximal parent” (the “maximal parent” here means that in some cases the direct parent–child relation cannot satisfy the problem's requirement of appearing twice, so we need the “maximal parent” to denote the nearest ancestor that makes it appear twice). After that, just do a normal DP and take the maximum.

// CF700E.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 401000;

int n;
char str[MAX_N];

namespace SAM
{

struct node
{
    int dep, link, ch[26], pos;
} nodes[MAX_N << 1];

int ptot = 1, last_ptr = 1;

void insert(int c, int idx)
{
    int pre = last_ptr, p = last_ptr = ++ptot;
    nodes[p].dep = nodes[pre].dep + 1, nodes[p].pos = idx;
    while (pre && nodes[pre].ch[c] == 0)
        nodes[pre].ch[c] = p, pre = nodes[pre].link;
    if (pre == 0)
        nodes[p].link = 1;
    else
    {
        int q = nodes[pre].ch[c];
        if (nodes[q].dep == nodes[pre].dep + 1)
            nodes[p].link = q;
        else
        {
            int clone = ++ptot;
            nodes[clone] = nodes[q], nodes[clone].dep = nodes[pre].dep + 1;
            nodes[p].link = nodes[q].link = clone;
            while (pre && nodes[pre].ch[c] == q)
                nodes[pre].ch[c] = clone, pre = nodes[pre].link;
        }
    }
}

} // namespace SAM

namespace SegmentTree
{

struct node
{
    int sum, lson, rson;
} nodes[MAX_N * 25];

int ptot;

void pushup(int p) { nodes[p].sum = nodes[nodes[p].lson].sum + nodes[nodes[p].rson].sum; }

int update(int qx, int l, int r, int p)
{
    if (p == 0)
        p = ++ptot;
    if (l == r)
    {
        nodes[p].sum++;
        return p;
    }
    int mid = (l + r) >> 1;
    if (qx <= mid)
        nodes[p].lson = update(qx, l, mid, nodes[p].lson);
    else
        nodes[p].rson = update(qx, mid + 1, r, nodes[p].rson);
    pushup(p);
    return p;
}

int merge(int x, int y, int l, int r)
{
    if (x == 0 || y == 0)
        return x + y;
    if (l == r)
    {
        nodes[x].sum += nodes[y].sum;
        return x;
    }
    int mid = (l + r) >> 1, p = ++ptot;
    nodes[p].lson = merge(nodes[x].lson, nodes[y].lson, l, mid);
    nodes[p].rson = merge(nodes[x].rson, nodes[y].rson, mid + 1, r);
    pushup(p);
    return p;
}

int query(int ql, int qr, int l, int r, int p)
{
    if (p == 0)
        return 0;
    if (ql <= l && r <= qr)
        return nodes[p].sum;
    int mid = (l + r) >> 1, ret = 0;
    if (ql <= mid)
        ret += query(ql, qr, l, mid, nodes[p].lson);
    if (mid < qr)
        ret += query(ql, qr, mid + 1, r, nodes[p].rson);
    return ret;
}

} // namespace SegmentTree

int roots[MAX_N << 1], bucket[MAX_N << 1], rnk[MAX_N << 1], top[MAX_N << 1], dp[MAX_N << 1];

int main()
{
    scanf("%d%s", &n, str + 1);
    for (int i = 1; i <= n; i++)
        SAM::insert(str[i] - 'a', i), roots[SAM::last_ptr] = SegmentTree::update(i, 1, n, roots[SAM::last_ptr]);
    for (int i = 1; i <= SAM::ptot; i++)
        bucket[SAM::nodes[i].dep]++;
    for (int i = 1; i <= SAM::ptot; i++)
        bucket[i] += bucket[i - 1];
    for (int i = 1; i <= SAM::ptot; i++)
        rnk[bucket[SAM::nodes[i].dep]--] = i;
    for (int i = SAM::ptot; i >= 1; i--)
        if (SAM::nodes[rnk[i]].link != 0)
            roots[SAM::nodes[rnk[i]].link] = SegmentTree::merge(roots[SAM::nodes[rnk[i]].link], roots[rnk[i]], 1, n);
    int ans = 1;
    for (int i = 2; i <= SAM::ptot; i++)
    {
        int u = rnk[i], fa = SAM::nodes[u].link;
        if (fa == 1)
        {
            dp[u] = 1, top[u] = u;
            continue;
        }
        int l = SAM::nodes[u].pos - SAM::nodes[u].dep + SAM::nodes[top[fa]].dep;
        int r = SAM::nodes[u].pos - 1;
        int x = SegmentTree::query(l, r, 1, n, roots[top[fa]]);
        if (x > 0)
            dp[u] = dp[fa] + 1, top[u] = u;
        else
            dp[u] = dp[fa], top[u] = top[fa];
        ans = max(ans, dp[u]);
    }
    printf("%d\n", ans);
    return 0;
}

[NOI2018] Your Name

This really is a disgusting problem. Restating the problem: within the string \(S[l\dots r]\), count the substrings of the string \(T\) that are not substrings of \(S\). First think about the case \(l = 1, r = n\): while building the suffix automaton of \(T\), we can run along in \(S\), each time recording the longest length that can match a prefix, and then the contribution of each node in \(SAM_T\) is:

\[ \max(0, dep[p_T] - \max(match_i, dep[fa[p_T]]) \]

where \(p_T\) is a node in \(SAM_T\).

Now for the intended solution: we definitely need a segment tree to maintain the set information, and then we can do something similar, except that we need to improve the handling of \(match_i\) to accommodate the interval information: when jumping upward by brute force for the LCP, check whether it is within the interval. Then it can be finished just like before.

// LOJ2720.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 1e6 + 2000, MAX_M = 2e7 + 200;

int n, q, limit[MAX_N];
char S[MAX_N], T[MAX_N];

namespace SegmentTree
{

struct node
{
    int sum, lson, rson;
} nodes[MAX_M];

int ptot, roots[MAX_N];

int update(int qx, int l, int r, int p)
{
    if (p == 0)
        p = ++ptot;
    nodes[p].sum++;
    if (l == r)
        return p;
    int mid = (l + r) >> 1;
    if (qx <= mid)
        nodes[p].lson = update(qx, l, mid, nodes[p].lson);
    else
        nodes[p].rson = update(qx, mid + 1, r, nodes[p].rson);
    return p;
}

int query(int ql, int qr, int l, int r, int p)
{
    if (p == 0)
        return 0;
    if (ql <= l && r <= qr)
        return nodes[p].sum;
    int ret = 0, mid = (l + r) >> 1;
    if (ql <= mid)
        ret += query(ql, qr, l, mid, nodes[p].lson);
    if (mid < qr)
        ret += query(ql, qr, mid + 1, r, nodes[p].rson);
    return ret;
}

int merge(int x, int y, int l, int r)
{
    if (x == 0 || y == 0)
        return x + y;
    int p = ++ptot, mid = (l + r) >> 1;
    nodes[p].sum = nodes[x].sum + nodes[y].sum;
    if (l == r)
        return p;
    nodes[p].lson = merge(nodes[x].lson, nodes[y].lson, l, mid);
    nodes[p].rson = merge(nodes[x].rson, nodes[y].rson, mid + 1, r);
    return p;
}

} // namespace SegmentTree

namespace SAM
{

struct node
{
    int dep, ch[26], link;
} nodes[MAX_N];

int last_ptr = 1, ptot = 1, bucket[MAX_N], rnk[MAX_N];

int newnode() { return ++ptot; }

void initialize_collection()
{
    for (int i = 1; i <= ptot; i++)
        bucket[nodes[i].dep]++;
    for (int i = 1; i <= ptot; i++)
        bucket[i] += bucket[i - 1];
    for (int i = 1; i <= ptot; i++)
        rnk[bucket[nodes[i].dep]--] = i;
    for (int i = ptot; i >= 1; i--)
        if (nodes[rnk[i]].link != 0)
            SegmentTree::roots[nodes[rnk[i]].link] = SegmentTree::merge(SegmentTree::roots[nodes[rnk[i]].link], SegmentTree::roots[rnk[i]], 1, n);
}

} // namespace SAM

namespace SAM_T
{

SAM::node nodes[MAX_N];
int ptot = 1, last_ptr = 1, pos[MAX_N];

void clear() { ptot = last_ptr = 1, memset(nodes[1].ch, 0, sizeof(nodes[1].ch)), nodes[1].dep = nodes[1].link = 0; }

int newnode()
{
    int p = ++ptot;
    memset(nodes[p].ch, 0, sizeof(nodes[p].ch));
    nodes[p].dep = nodes[p].link = 0, pos[p] = 0;
    return p;
}

} // namespace SAM_T

int insert(int c, int &last_ptr, int (*newnode)(), SAM::node *nodes, bool toggle = false)
{
    int pre = last_ptr, p = last_ptr = newnode();
    nodes[p].dep = nodes[pre].dep + 1;
    if (toggle)
        SAM_T::pos[p] = nodes[p].dep;
    while (pre && nodes[pre].ch[c] == 0)
        nodes[pre].ch[c] = p, pre = nodes[pre].link;
    if (pre == 0)
        nodes[p].link = 1;
    else
    {
        int q = nodes[pre].ch[c];
        if (nodes[q].dep == nodes[pre].dep + 1)
            nodes[p].link = q;
        else
        {
            int clone = newnode();
            nodes[clone] = nodes[q];
            if (toggle)
                SAM_T::pos[clone] = SAM_T::pos[q];
            nodes[clone].dep = nodes[pre].dep + 1;
            nodes[q].link = nodes[p].link = clone;
            while (pre && nodes[pre].ch[c] == q)
                nodes[pre].ch[c] = clone, pre = nodes[pre].link;
        }
    }
    return p;
}

int main()
{
    freopen("name.in", "r", stdin);
    freopen("name.out", "w", stdout);
    scanf("%s", S + 1), n = strlen(S + 1);
    for (int i = 1; i <= n; i++)
    {
        insert(S[i] - 'a', SAM::last_ptr, SAM::newnode, SAM::nodes);
        SegmentTree::roots[SAM::last_ptr] = SegmentTree::update(i, 1, n, SegmentTree::roots[SAM::last_ptr]);
    }
    SAM::initialize_collection();
    scanf("%d", &q);
    while (q--)
    {
        int l, r, m;
        scanf("%s%d%d", T + 1, &l, &r);
        SAM_T::clear(), m = strlen(T + 1);
        for (int i = 1, p = 1, clen = 0; i <= m; i++)
        {
            int c = T[i] - 'a';
            insert(c, SAM_T::last_ptr, SAM_T::newnode, SAM_T::nodes, true);
            while (true)
            {
                if (SAM::nodes[p].ch[c] && SegmentTree::query(
                                               l + clen, r,
                                               1, n,
                                               SegmentTree::roots[SAM::nodes[p].ch[c]]))
                {
                    clen++, p = SAM::nodes[p].ch[c];
                    break;
                }
                if (clen == 0)
                    break;
                clen--;
                if (clen == SAM::nodes[SAM::nodes[p].link].dep)
                    p = SAM::nodes[p].link;
            }
            limit[i] = clen;
        }
        long long ans = 0;
        for (int i = 2; i <= SAM_T::ptot; i++)
            ans += max(0, SAM_T::nodes[i].dep - max(SAM_T::nodes[SAM_T::nodes[i].link].dep, limit[SAM_T::pos[i]]));
        printf("%lld\n", ans);
    }
    return 0;
}

[HAOI2016] Finding Identical Characters

The approach at first glance: concatenate the two strings, then go through every Endpos set, find in a segment tree the numbers of occurrences in the first half and in the second half, and multiply them.

Intended solution: you actually don't need a complicated segment tree; you just need to record Size separately, and while inserting the second string, walk on the SAM and reset Last_ptr.

// LOJ2064.cpp
#include <bits/stdc++.h>
#define ll long long

using namespace std;

const int MAX_N = 5e5 + 200;

struct node
{
    int ch[26], siz[2], link, dep;
} nodes[MAX_N << 1];

int last_ptr = 1, ptot = 1, bucket[MAX_N << 1], n1, n2, rnk[MAX_N << 1];
ll ans;
char str1[MAX_N], str2[MAX_N];

void insert(int c, int typ)
{
    int pre = last_ptr, p = last_ptr = ++ptot;
    nodes[p].dep = nodes[pre].dep + 1;
    if (typ == 0)
        nodes[p].siz[0] = 1;
    while (pre && nodes[pre].ch[c] == 0)
        nodes[pre].ch[c] = p, pre = nodes[pre].link;
    if (pre == 0)
        nodes[p].link = 1;
    else
    {
        int q = nodes[pre].ch[c];
        if (nodes[q].dep == nodes[pre].dep + 1)
            nodes[p].link = q;
        else
        {
            int clone = ++ptot;
            nodes[clone] = nodes[q], nodes[clone].siz[0] = nodes[clone].siz[1] = 0;
            nodes[clone].dep = nodes[pre].dep + 1;
            nodes[p].link = nodes[q].link = clone;
            while (pre && nodes[pre].ch[c] == q)
                nodes[pre].ch[c] = clone, pre = nodes[pre].link;
        }
    }
}

void radixSort()
{
    for (int i = 1; i <= ptot; i++)
        bucket[nodes[i].dep]++;
    for (int i = 1; i <= ptot; i++)
        bucket[i] += bucket[i - 1];
    for (int i = ptot; i >= 1; i--)
        rnk[bucket[nodes[i].dep]--] = i;
    for (int i = ptot; i >= 1; i--)
        if (nodes[rnk[i]].link != 0)
        {
            nodes[nodes[rnk[i]].link].siz[0] += nodes[rnk[i]].siz[0];
            nodes[nodes[rnk[i]].link].siz[1] += nodes[rnk[i]].siz[1];
        }
    for (int i = 1; i <= ptot; i++)
        ans += 1LL * nodes[i].siz[0] * nodes[i].siz[1] * (nodes[i].dep - nodes[nodes[i].link].dep);
}

int main()
{
    scanf("%s%s", str1 + 1, str2 + 1);
    n1 = strlen(str1 + 1), n2 = strlen(str2 + 1);
    for (int i = 1; i <= n1; i++)
        insert(str1[i] - 'a', 0);
    last_ptr = 1;
    for (int i = 1, p = 1; i <= n2; i++)
    {
        insert(str2[i] - 'a', 1);
        p = nodes[p].ch[str2[i] - 'a'];
        nodes[p].siz[1] = 1;
    }
    radixSort();
    printf("%lld\n", ans);
    return 0;
}

[Yali Training Camp 2017 Day1] String

This problem is so hard. First I need to introduce a standard trick that has shown up in data structures: square-root case splitting. For two parameters whose product is fixed, there may be a hidden square-root time complexity. For example: CF103D.

On to the intended solution: first build the SAM. If the string size is smaller than the set block size, we consider the following way of handling it:

A small \(k\) means that the positions of the given \(m\) intervals are all fairly concentrated (?), so we open a three-dimensional space to store the indices of the intervals, then enumerate substrings in \(k^2\) and walk on the SAM. If the current substring qualifies, then in the three-dimensional space we find how many interval indices are contained in the query \([l, r]\).

If not:

We consider computing, for each position of the query string, the maximum match length extending backward from it and its node on the SAM; then for a query we only need to enumerate from \(a\) to \(b\), and from the rightmost point jump up to the SAM node closest to the leftmost point.

// LOJ6031.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 2e6 + 200, block_size = 330;

int head[MAX_N], current, fa[20][MAX_N], li[MAX_N], ri[MAX_N], m, n, q, k;
int cpos[MAX_N], clen[MAX_N];
char str[MAX_N], w[MAX_N];

struct edge
{
    int to, nxt;
} edges[MAX_N << 1];

void addpath(int src, int dst)
{
    edges[current].to = dst, edges[current].nxt = head[src];
    head[src] = current++;
}

namespace SAM
{

struct node
{
    int ch[26], link, dep, siz;
} nodes[MAX_N << 1];

int ptot = 1, last_ptr = 1;

void insert(int c)
{
    int pre = last_ptr, p = last_ptr = ++ptot;
    nodes[p].dep = nodes[pre].dep + 1, nodes[p].siz = 1;
    while (pre && nodes[pre].ch[c] == 0)
        nodes[pre].ch[c] = p, pre = nodes[pre].link;
    if (pre == 0)
        nodes[p].link = 1;
    else
    {
        int q = nodes[pre].ch[c];
        if (nodes[q].dep == nodes[pre].dep + 1)
            nodes[p].link = q;
        else
        {
            int clone = ++ptot;
            nodes[clone] = nodes[q], nodes[clone].dep = nodes[pre].dep + 1;
            nodes[p].link = nodes[q].link = clone, nodes[clone].siz = 0;
            while (pre && nodes[pre].ch[c] == q)
                nodes[pre].ch[c] = clone, pre = nodes[pre].link;
        }
    }
}

void build_graph()
{
    for (int i = 1; i <= ptot; i++)
        if (nodes[i].link != 0)
            addpath(nodes[i].link, i), fa[0][i] = nodes[i].link;
}

void dfs(int u)
{
    for (int i = 1; i <= 19; i++)
        fa[i][u] = fa[i - 1][fa[i - 1][u]];
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        dfs(edges[i].to), nodes[u].siz += nodes[edges[i].to].siz;
}

} // namespace SAM

void solve1()
{
    vector<int> buc[block_size][block_size];
    for (int i = 1; i <= m; i++)
        buc[li[i]][ri[i]].push_back(i);
    while (q--)
    {
        int a, b;
        long long ans = 0;
        scanf("%s%d%d", w + 1, &a, &b);
        a++, b++;
        for (int i = 1; i <= k; i++)
            for (int j = i, p = 1; j <= k; j++)
            {
                p = SAM::nodes[p].ch[w[j] - 'a'];
                if (p == 0)
                    break;
                int l = lower_bound(buc[i][j].begin(), buc[i][j].end(), a) - buc[i][j].begin();
                int r = upper_bound(buc[i][j].begin(), buc[i][j].end(), b) - buc[i][j].begin();
                ans += 1LL * (r - l) * SAM::nodes[p].siz;
            }
        printf("%lld\n", ans);
    }
}

void solve2()
{
    while (q--)
    {
        int a, b;
        long long ans = 0;
        scanf("%s%d%d", w + 1, &a, &b);
        a++, b++;
        for (int i = 1, p = 1, len = 0; i <= k; i++)
        {
            while (p && SAM::nodes[p].ch[w[i] - 'a'] == 0)
                p = SAM::nodes[p].link, len = SAM::nodes[p].dep;
            if (p == 0)
                p = 1;
            else
                p = SAM::nodes[p].ch[w[i] - 'a'];
            len += (p != 1);
            cpos[i] = p, clen[i] = len;
        }
        for (int idx = a; idx <= b; idx++)
        {
            int p = cpos[ri[idx]], dist = ri[idx] - li[idx] + 1;
            if (dist > clen[ri[idx]])
                continue;
            else if (dist == clen[ri[idx]])
            {
                ans += SAM::nodes[p].siz;
                continue;
            }
            for (int i = 19; i >= 0; i--)
                if (fa[i][p] && SAM::nodes[fa[i][p]].dep >= dist)
                    p = fa[i][p];
            ans += SAM::nodes[p].siz;
        }
        printf("%lld\n", ans);
    }
}

int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d%d%d%d%s", &n, &m, &q, &k, str + 1);
    for (int i = 1; i <= n; i++)
        SAM::insert(str[i] - 'a');
    SAM::build_graph(), SAM::dfs(1);
    for (int i = 1; i <= m; i++)
        scanf("%d%d", &li[i], &ri[i]), li[i]++, ri[i]++;
    if (1LL * k <= block_size)
        solve1();
    else
        solve2();
    return 0;
}