---
id: 2902
lang: en
translation_of: index.md
source_sha256: 6e28ff6d5c45dc6f50770586a62c1ae1a8164ce83c1b23bc2856c0abfdb0d5d7
title: "[2021 CCPC Guilin] J - Suffix Automaton"
description: "Find the k-th distinct substring, ordered by length then lexicographically, via a suffix automaton's link tree, a Fenwick tree and a heap."
tags: ["OI","Heap","Fenwick Tree","SAM","Suffix Automaton"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "取所有后缀后 clen 的结果 rendered literally as “taking the last clen of every suffix”."
---

## Brief Statement

Given a string $S$. Define an ordering on the distinct substrings of this string:

- When the lengths differ, the shorter one goes in the lower position.
- When the lengths are equal, sort lexicographically.

Simply put, length is the first key and lexicographic order is the second key. Now you are given $Q$ queries; each query asks for the first occurrence position of the substring ranked $k$ under this ordering.

### Constraints

$1 \leq |S|, Q \leq 10^6, 1 \leq k \leq 10^{12}$

<!--more-->

## Main Idea

This problem looks pretty much like <span class="slang" data-zh="板子" data-gloss="bǎnzi, “board”. A prepared template implementation of a standard algorithm.">template code</span>, and the problem even hints that it's a suffix automaton. But when I wrote it myself, there were actually quite a lot of details. This problem counts as a flexible application of the suffix automaton's link tree.

First, let's roughly picture what this ordering looks like. Obviously, it must be made of several segments of equal-length strings joined end to end, and within each segment the strings follow lexicographic order. The brute-force idea is to process all the substrings and then answer.

So how does this combine with the suffix automaton? We know the number of these substrings is huge in magnitude, but the suffix automaton can still represent them well, because it can compress substrings.

We know the suffix automaton's link tree: each endpos set, as a parent, connects to its subsets via tree edges, so the intersection of the suffixes of the endpos sets represented by a set's child nodes is the longest suffix represented by that set, and this length is recorded in the node's dep. However, the difference between the longest suffixes represented by a child and its parent is not always exactly one, and this is how the suffix automaton compresses substrings.

We can reverse the string and build the suffix automaton, so that all the suffixes become prefixes. Then how can we locate the endpos set containing the string ranked $k$?

We can consider a not-so-great approach: we can try to list the ordering of these substrings, but in a compressed form. We first set the current length to $clen = 0$, then add the nodes on the second level of the link tree to the “candidate set” ($pset$). At this point, we assign the shortest suffix length in the candidate set to $clen$, which means the current candidate set fully contains all suffixes of length at least $clen$ (the candidate set may have suffixes longer than this, but definitely none shorter). Then we sort the candidate set lexicographically (really it's the result of taking the last $clen$ of every suffix, but obviously sorting directly lexicographically doesn't affect the result). Now the size of the set is $|pset|$, so we can check whether $k$ is in $[1, clen \times |pset|]$.

In fact, at this point we have already represented, in compressed form, $clen$ segments of the complete ordering. To recap, the first of these segments is the sub-suffixes of length $1$ of all the suffixes in the candidate set after sorting lexicographically. Then the second segment is the sub-suffixes of length $2$ of all the suffixes in the candidate set after sorting lexicographically.

Once we reach $clen$, the candidate set contains at least one suffix that cannot represent suffixes longer than $clen$. At that point we remove it from the set and add that suffix's child endpos sets.

After $clen$ has been checked, we move on to the next round. Now $clen$ needs to be updated to the shortest suffix length in the current “candidate set”, and the old $clen$ is assigned to $plen$. Now we check whether $k$ is in $[part_1 + 1, part_1 + (clen - plen) \times |pset|]$, where $part_1$ is the number of substrings in the previous round. Why $clen - plen$? Because this length is exactly the length compressed by the suffix automaton, and now we just unfold it.

Keep processing like this, and there will always come a moment when $k$ hits an interval. When it hits, we use the modulo operation to find the position, within the cycle, of the suffix containing the string ranked $k$, and use division to compute the number of cycles, which also gives the exact length of that string. While maintaining the SAM, also maintain the earliest occurrence position, then add things up and the answer comes out.

That's how to handle it once. What? You want to handle it $Q$ times? It's actually obvious: after going offline, the answers can be computed in order. As for how to maintain the “candidate set”, that is, how to quickly find the lexicographically $k$-th smallest suffix, while also knowing which suffixes have the minimum depth.

The author used two simple data structures here to maintain it. First, a dfs on the link tree gives the relative lexicographic order of the children under a parent, and running one more dfs to record the dfs order gives the lexicographic order. Finding the index of the $k$-th smallest suffix can in fact be maintained with a Fenwick tree; meanwhile, to maintain the suffixes with the minimum depth, a priority queue is all you need.

Next, please see the code.

## Code

```cpp
// J.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 1e6 + 200;

typedef long long ll;
typedef pair<ll, int> pli;
typedef pair<int, int> pii;

int n, Q, tree[MAX_N << 1], anti[MAX_N << 1];
char str[MAX_N];
pli queries[MAX_N];
pii ansBox[MAX_N];

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

int ptot = 1, last_ptr = 1, bucket[MAX_N << 1], rnk[MAX_N << 1];
vector<int> G[MAX_N << 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;
        }
    }
}

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 = 1; i <= ptot; i++)
        rnk[bucket[nodes[i].dep]--] = i;
    for (int i = 2; i <= ptot; i++)
        G[nodes[rnk[i]].link].push_back(rnk[i]);
}

int cnt;

void dfs1(int u)
{
    for (int v : G[u])
    {
        dfs1(v);
        nodes[u].pos = min(nodes[u].pos, nodes[v].pos);
        nodes[v].lc = str[nodes[v].pos + nodes[u].dep] - 'a';
    }
    sort(G[u].begin(), G[u].end(), [](const int &lhs, const int &rhs)
         { return nodes[lhs].lc < nodes[rhs].lc; });
}

void dfs2(int u)
{
    cnt++, nodes[u].dfn = cnt, anti[cnt] = u;
    for (int v : G[u])
        dfs2(v);
}

inline int lowbit(int x) { return x & -x; }

void update(int x, int d)
{
    for (; x <= ptot; x += lowbit(x))
        tree[x] += d;
}

int kth(int k)
{
    int ret = 0;
    for (int i = 22; i >= 0; i--)
    {
        ret += (1 << i);
        if (ret >= ptot || k <= tree[ret])
            ret -= (1 << i);
        else
            k -= tree[ret];
    }
    return ret + 1;
}

int main()
{
    scanf("%s", str + 1), n = strlen(str + 1), scanf("%d", &Q);
    for (int i = n; i >= 1; i--)
        insert(str[i] - 'a', i);
    for (int i = 1; i <= Q; i++)
        scanf("%lld", &queries[i].first), queries[i].second = i;
    sort(queries + 1, queries + 1 + Q), radixSort(), dfs1(1), dfs2(1);
    int qptr = 1, clen = 0, plen = 0;
    ll acc = 0;
    priority_queue<pii> pq;
    for (int v : G[1])
        pq.push(make_pair(-nodes[v].dep, v)), update(nodes[v].dfn, 1);
    while (!pq.empty())
    {
        clen = -pq.top().first;
        int cycle_len = clen - plen, cycle_width = pq.size();
        ll amount = 1LL * cycle_len * cycle_width;
        while (qptr <= Q && queries[qptr].first > acc && queries[qptr].first <= acc + amount)
        {
            ll order = queries[qptr].first - acc;
            ll nxt = (order - 1) % cycle_width, slen = (order - 1) / cycle_width;
            int id = anti[kth(nxt + 1)];
            ansBox[queries[qptr].second] = make_pair(nodes[id].pos, nodes[id].pos + clen + slen - 1);
            qptr++;
        }
        while (!pq.empty() && pq.top().first == -clen)
        {
            int u = pq.top().second;
            pq.pop();
            update(nodes[u].dfn, -1);
            for (int v : G[u])
                pq.push(make_pair(-nodes[v].dep, v)), update(nodes[v].dfn, 1);
        }
        plen = clen, acc += amount;
    }
    for (int i = 1; i <= Q; i++)
        if (ansBox[i].first == 0 && ansBox[i].second == 0)
            puts("-1 -1");
        else
            printf("%d %d\n", ansBox[i].first, ansBox[i].second);
    return 0;
}
```
