PrevNext

很多问题都可以用后缀数组、后缀自动机或后缀树解决。使用不同的数据结构,实现难度可能略有差别。

后缀自动机

后缀自动机是一张有向无环单词图(DAWG),图中的每条路径对应原字符串的一个不同子串。

Resources
CF

后缀自动机讲解

cp-algo

优秀的后缀自动机教程

CF

更多练习题!

代码实现

Resources
Benq

后缀树

后缀树是一棵包含字符串所有后缀的字典树。朴素存储需要 O(N2)\mathcal{O}(N^2) 空间,但通过路径压缩,可以在线性空间内表示并构建它。

Resources
SO

示例与图解

CF

Ukkonen 算法简介与代码

代码实现

Resources
Benq

基于上文 adamant 的实现

cp-algo

Ukkonen 算法实现

从后缀树生成后缀数组

对后缀树进行深度优先遍历,即可生成后缀数组。

int N, sa[MN], ctr; // length of string, suffix array, counter
struct Edge {
public:
int n, l, r; // node, edge covers s[l..r]
explicit operator bool() const { return n != -1; }
} c[MN * 2][26]; // edges of a suffix tree
void dfs(int n = 0, int d = 0) {
bool c = 0; // Has child. If false, then this node is a leaf

从后缀数组生成后缀树

上述过程也可以反向进行。后缀数组中的每个元素都对应后缀树的一个叶子,而 LCP 数组包含后缀数组中相邻两个元素的最近公共祖先信息。利用这两部分信息,可以在线性时间内由后缀数组构建后缀树。

实用提示

在字符串末尾添加 $ 或 - 等“终止符”,通常可以大幅简化后缀结构。下方示例会显式加入终止符。

int N;
char s[MN];
int sa[MN]; // suffix array
int lcp[MN]; // lcp[i] stores the longest common prefix between s[sa[i-1]..]
// and s[sa[i]..]
Edge c[MN * 2][MK]; // edges of suffix tree
int d[MN * 2]; // length of string corresponding to a node in the suffix tree
int q[MN * 2], Q, ctr,
rm[MN]; // q is used as stack. ctr counts number of nodes in tree

从后缀自动机生成后缀树

后缀树和后缀自动机之间有一个有趣的关系:后缀自动机的后缀链接树等价于反转字符串的后缀树。由于后缀自动机比后缀树更容易构建,我们可以利用这一关系,以线性时间构建后缀树!

char s[MN]; // string
int ord[MN]; // nodes representing prefixes of the string s
int u[MN * 2]; // whether the node has already been created
int l[MN * 2]; // link in suffix automaton
Edge c[MN * 2][27]; // edge of suffix tree (not automaton; structure of
// automaton is not necessary to build stree)
void build_tree() {
s[N] = 26; // terminator
for (int i = N; i >= 0; --i) ord[i] = append(ord[i + 1], s[i]);
for (int i = 0, x, r, l; i <= N; ++i) {

示例:Standing Out

重点例题 – 继续学习之前,请先尽力独立解决这道题!

使用后缀自动机解 Standing Out

#include <cstdio>
#include <cstring>
#include <vector>
FILE *IN, *OUT;
typedef long long ll;
const int MN = 1e5 + 10, MM = MN * 2;
char s[MN];
std::vector<int> down[MM];
int N, v[MM], c[MM][26], l[MM], d[MM], topo[MM], T, X;

后缀结构练习题(数组、自动机与树)

StatusSourceProblem NameDifficultyTags
CFEasy
Show TagsSuffix Structures
KattisEasy
onlinejudge.orgEasy
SPOJEasy
Show TagsSuffix Structures
CFEasy
HEMedium
Show TagsSuffix Structures
CFMedium
Show TagsSuffix Structures
Balkan OIMedium
Show TagsDP, Suffix Structures
CFHard
Show TagsSuffix Structures
CFHard
Show TagsSuffix Structures
CFHard
Show TagsSuffix Structures
CFVery Hard
Show TagsDP, Suffix Structures
CFVery Hard
Show TagsSuffix Tree
CFVery Hard
Show TagsSuffix Structures

扩展回文树

练习题

StatusSourceProblem NameDifficultyTags
CFVery Hard
Show TagsPalindromic Tree
CFInsane
Show TagsPalindromic Tree

Module Progress:

PrevNext