跳到正文

个人记录

后缀自动机学习笔记

xtx1092515503约 50 分钟
原文
文章信息与版本

文章信息

发布
2021年1月10日
收录
2025年12月12日
更新
2026年11月10日
篇幅
约 50 分钟
获赞
2

版本

  1. v1当前

这里是SAM学习笔记。


SAM是Suffix Automaton 萨菲克斯自动马桶的缩写,其中文翻译是后缀自动机。

顾名思义,其是一个自动机。SAM接受一个串,当且仅当其是母串 SS 的后缀。

这里我们给出一些定义:

所有使用黑板粗体格式的字符 S\mathbb{S},表示集合;

所有使用大写格式的字符 SS,表示字符串;

所有使用黑体格式的字符 s\mathbf{s},表示字符型变量;

所有使用正体格式的字符 s\text{s},表示一种定义;

所有使用小写格式的字符 ss,表示整型变量;

所有被代码框框起来的字符 s,表示 s 这个字符。ss 之类,可能表示字符串,也可能表示一段代码,视具体情形而定。

所有无任何格式的字符 s,表示一种专有名词。

定义字符串的下标从 00 开始(若没有特殊说明)。

定义 preS(i)\text{pre}_S(i) 为 字符串 SS 长度为 ii 的前缀。若已经定义了 SS,也可以简写成 pre(i)\text{pre}(i) 或 prei\text{pre}_i。

定义 sufS(i)\text{suf}_S(i) 同理,表示后缀。

定义母串 SS 为后缀自动机所作用的串。

定义 ∣S∣|S| 符号表示串 SS 的长度。更多的时候,会专门定义一个 nn 来表示。同时,其也可以被用于表示一个集合中元素的数量。

O.后缀自动机

模板的讲解。

首先,若我们暴力地想建出SAM,明显点数是 O(∣S∣2)O(|S|^2) 的。

唯一的优化方式即为缩减状态数。

定义 endposS(T)\text{endpos}_S(T) 是一个串 TT 在串 SS 中所有出现的位置的结尾下标。明显,其是一集合。例如,若 TT 为 ab,SS 为 abab,则 endposS(T)={1,3}\text{endpos}_S(T)=\{1,3\}。在指明 SS 的时候可以忽略下标。

我们发现,在 SS 的众多子串中,有很多串的 endpos\text{endpos} 集合是相等的。例如,在上文的例子中,ab 和 b 的 endpos\text{endpos} 集合就是相同的。

我们把两个串 T1,T2T_1,T_2 endpos\text{endpos} 集合相等的关系称作 endpos\text{endpos} 等价,符号表示为 T1≡ST2T_1\equiv_ST_2。指明 SS 时可忽略下标。

我们发现,通过上述的 ≡\equiv 关系,我们可以将 SS 的所有子串分作众多 endpos\text{endpos} 等价类,简称类。

则有如下定理:

定理1:等价类中任意两个串,其中一个是另一个的后缀\boxed{\text{定理1:等价类中任意两个串,其中一个是另一个的后缀}}

这是非常显然的——更长的串都匹配上了,更短的串还能匹配不上吗?

由 (1)(1),便可得到定理 (2)(2):

定理2:对于两个串T1,T2(∣T1∣≥∣T2∣),endpos(T1)⊆endpos(T2) 或 endpos(T1)∪endpos(T2)=∅\boxed{\text{定理2:对于两个串}T_1,T_2(|T_1|\geq|T_2|),\text{endpos}(T_1)\subseteq\text{endpos}(T_2)\text{ 或 }\text{endpos}(T_1)\cup\text{endpos}(T_2)=\varnothing}

实际上是 (1)(1) 的逆命题。证明类似。

由 (1)(1) 和 (2)(2),可以得到 (1)(1) 更强的推论:

定理3:等价类中所有串按照长度从大到小排序,后一个是前一个的长度减一的后缀\boxed{\text{定理3:等价类中所有串按照长度从大到小排序,后一个是前一个的长度减一的后缀}}

于是我们定义 min⁡(S)\min(\mathbb{S}) 为一集合 S\mathbb{S} 中长度最短的串,max⁡(S)\max(\mathbb{S}) 为最长的。

考虑往 max⁡(S)\max(\mathbb{S})(设其为 PP) 开头添加一个字符,则会得到一个新的串 QQ。明显,endpos(Q)⊂S\text{endpos}(Q)\subset\mathbb{S}。而添加不同的字符,便会得到不同的 QQ——明显这些 QQ,因为其长度相等而又不完全相同,故其 endpos\text{endpos} 集合全都无交。并且,所有这样的 QQ 的 endpos\text{endpos} 集合的并会得到 S\mathbb{S}。

这也意味着这样的操作是一个划分操作——每个 S\mathbb{S} 中的串归入且仅归入一个集合。明显,划分操作是有父子关系的,故所有集合实际上构成了一棵树,称其为 parent tree。同时,在划分的时候,S\mathbb{S} 中会至少有一个元素被分到了大小为 11 的集合。

而这就意味着,总节点数不会超过 2n2n(有 nn 个大小为 11 的集合;根集合大小为 nn,每次划分至少损失掉一个元素)!那就意味着,如果我们有较快的算法建出parent tree,是可以存得下其中所有东西的!

但是,知道有parent tree这种东西,又有什么用呢?

我们将看到,parent tree中所有节点,刚好可以被看作是自动机上节点! 空串节点可被看作是DAG的源点,所有包含母串的集合 S\mathbb{S} 都是终止节点。可以发现,终止节点形成parent tree中一条从源点到叶子的链。

在自动机中,我们需要保证,一条从源点到某个点 ii 的路径上所有边上的字符依次拼接起来会刚好得到 ii 点所对应集合里所有的串,也即自动机上的边上储存的是字符;而parent tree,因为在分析中我们是往前面不停添加字符,所以边上存的都是字符串。在parent tree上沿着边向子树中走,相当于往当前集合中的所有串的开头插入一个字符串;在自动机上沿着边走,则相当于往当前集合中所有串的结尾插入一个字符。这部分也可以类别AC自动机和fail树的关系(尽管二者的相似之处很少,除了都是一个自动机和一个树以外就没别的相同之处了)

我们已经保证自动机的点数是 O(n)O(n) 的了;但是如何保证其边数也符合要求呢?

事实上,其边数也是 O(n)O(n) 的。

我们考虑母串的全部后缀。明显,只需要保证每个后缀都能有一条从根到其代表节点的路径,即可拍胸脯保证这是一个合法的SAM了(因为这就是SAM的定义呀)。与此同时,我们不仅可以从源点出发正着跑路径,也可以从终止节点出发倒着跑路径——二者是等价的。

我们考虑对自动机求出其任意一棵生成树,并通过往生成树中加入新边来复原出自动机。然后,我们考虑遍历每个终止节点,并且按照某种顺序遍历该终止节点对应集合内所有的字符串。

如果对于其中一个串,存在一条从根到该终止节点的路径来表示该串,显然该串已经被check过合法了,可以跳过;

否则,即不存在一条这样的路径(尚未被添加入生成树张成的自动机中)。我们考虑将这条路径上尚未被添加的边(因为已经有一棵生成树,所以最多只有一条缺失的边)加入自动机中。这时,其parent tree中父亲、祖父,乃至所有祖先的集合中,当前字符串的后缀字符串,其也有一条路径同时被铺出来了(尽管不一定是原本自动机中的路径,但是只要有一条路径就行了)。之后,考虑再check下一个串即可。可以发现,此过程添加的边不会超过 ∣endpos(S)∣|\text{endpos}(\mathbb{S})| 的大小。而所有后缀中,一条边最多只会被加一次,所以总边数就是后缀数量,也即 O(n)O(n) 的。

后缀自动机的构造是在线的,增量的。这意味着可以在任意时刻,往任意节点后面添加字符(也就意味着可以很容易用它来实现树上SAM,或是多串SAM之类)。

一个典型的SAM长这样:

如图,底下一溜节点是原串的前缀,它们是一定存在于自动机里的(即parent tree中一整条终止节点路径)。而上面的节点,以及那些虚线的边,是不一定存在,也不一定是这么连接的。

我们定义一个集合 S\mathbb{S} 的 max⁡(S)\max(\mathbb{S}) 的长度为 len(S)\text{len}(\mathbb{S})。明显,parent tree中,集合 S\mathbb{S} 有且仅有一个父亲,称作 fa(S)\text{fa}(\mathbb{S})。则,∣min⁡(S)∣|\min(\mathbb{S})|,应为 len(fa(S))+1\text{len}\Big(\text{fa}(\mathbb{S})\Big)+1,依照我们上面关于添加字符的分析。这就意味着我们只需对于集合 S\mathbb{S} 储存其父亲和其最大串的长度就能知道其最小串的长度了。它们将在建SAM时派上大用处。

以下,会照着程序解释。

C++
struct Suffix_Automaton{int ch[26],len,fa;}t[N<<1];//a SAM has 2n nodes!!!
int cnt=1;
int Add(int x,int c){//add a character c after node x,return the index.
	int xx=++cnt;//the index of the newly-added node
	t[xx].len=t[x].len+1;//the maximal length of strings in xx.
	for(;x&&!t[x].ch[c];x=t[x].fa)t[x].ch[c]=xx;
	if(!x){t[xx].fa=1;return xx;}
	int y=t[x].ch[c];
	if(t[y].len==t[x].len+1){t[xx].fa=y;return xx;}
	int yy=++cnt;t[yy]=t[y];
	t[yy].len=t[x].len+1;
	t[y].fa=t[xx].fa=yy;
	for(;x&&t[x].ch[c]==y;x=t[x].fa)t[x].ch[c]=yy;
	return xx;
}

首先,记原来的串为 SS,加完新字符后的串为 S′S'。显然,依照我们上述推论,S′S' 自身所对应的状态是一定在自动机里的,但是它目前不在,所以建一个新点 xxxx 表示 S′S' 串本身,其长度为 ∣S∣+1|S|+1。

在添加完一个 c\mathbf{c} 后(注意此处 c\mathbf{c} 是一个字符,所以使用黑体),明显受到影响的只有 S′S' 的后缀(或者说 SS 的所有后缀再加上 c\mathbf{c})。

然后,不断地跳 xx 的父亲。因为 xx 是旧串的母串节点,所以 xx 的所有祖先就全是终止节点,即所有旧串的后缀。若当前的 xx 没有一个 c\mathbf{c} 的儿子,该后缀后面加上 c\mathbf{c} 就能得到 S′S' 的后缀,故在自动机上连一条边 (x,xx)(x,xx)(回忆一下,后缀自动机的边的意义是在结尾处添加字符),然后继续遍历其祖先。

如果一路跳最终跳到了根,显然整个串中都没有出现过 c\mathbf{c}。因此直接令 xx 的父亲为根即可。

否则,即其存在一个 c\mathbf{c} 儿子,即为代码中的 yy。

若 t[y].len==t[x].len+1 成立,则应有 max⁡(y)=max⁡(x)+c\max(y)=\max(x)+\mathbf{c}。而 xx 是旧串后缀,故 yy 表示新串后缀。因此,yy 与 xxxx 定义相同。但是 xxxx 在一路跳上去的过程中已经被设作了一堆东西的儿子,所以为了不再把它设一遍,我们直接认 yy 作父亲。

于是,下面就有 t[y].len!=t[x].len+1。而因为parent tree中的长度是随着深度增加而递增的,故实际上是t[y].len>t[x].len+1。

此时,考虑 max⁡(x)+c\max(x)+\mathbf{c}。明显,其应该属于 yy,但是其并不属于新串后缀(不然会直接跳到它所属节点上)。也即,yy 节点所属集合中,不全是可以添加 c\mathbf{c} 的串。因而,我们必须将 yy 分作两个集合,一个作为 xx 的 c\mathbf{c} 儿子,一个变成了 xxxx 的兄弟,也即 xx 的孙子。

我们选择,另开一个新节点 yyyy 作为 xx 的 c\mathbf{c} 儿子,然后用 yy 本身作为 yyyy 的儿子。则 xx 以及 xx 祖先中所有出现过的 yy 边(明显其应该是一条从 xx 往上的链)都应该被更换成 yyyy,然后令 len(yy)=len(x)+1\text{len}(yy)=\text{len}(x)+1。

那问题来了,为什么我们不交换 yy 和 yyyy 的定义呢?因为 yy 链可能在 xx 以下还有部分,但从 xx 出发只能找到其父亲上的 yy 链,却找不到儿子处的 yy 链。所以我们只能将父端的 yy 换成 yyyy,而不能将子端的 yy 换成 yyyy。

于是以上就是模板的全部内容。

可以发现,后缀自动机的复杂度是 O(n∣Σ∣)O(n|\Sigma|) 的,其中 ∣Σ∣|\Sigma| 是字符集大小。通过使用 map<int,int> 来储存儿子们,可以将复杂度优化至 nlog⁡∣Σ∣n\log|\Sigma|。但是对于平时的 2626 个字母来说,用了反而会更慢。

I.【模板】后缀自动机 (SAM)

虽说是模板但也不是纯粹板子!

SAM应用1:求一个子串的出现次数(相当于字符串匹配)。

因为同一个 endpos\text{endpos} 类中所有东西的结束集合都是相同的,故它们在母串中的出现次数也是相同的。因此,在该类中就应该贪心地选择最长的串,也即 len\text{len}。

那么我们如何求出一个 endpos\text{endpos} 类中所有东西的出现次数呢?考虑Parent Tree。

Parent Tree的实质是往一个集合中的串的开头添加新字符的过程。于是,我们考虑DP。设 fif_i 表示集合 ii 中所有串的出现次数。则 fi=1+∑j是i的儿子fjf_i=1+\sum\limits_{j\text{是}i\text{的儿子}}f_j。其中,那个 11 是指不加任何数的串本身。

时间复杂度 O(n∣Σ∣)O(n|\Sigma|)。

代码:

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1001000;
struct Suffix_Automaton{int ch[26],len,fa;}t[N<<1];//a SAM has 2n nodes!!!
int f[N<<1];
int cnt=1;
int Add(int x,int c){//add a character c after node x,return the index.
	int xx=++cnt;//the index of the newly-added node
	f[xx]=1;//stands that x is a finishing point
	t[xx].len=t[x].len+1;//the maximal length of strings in xx.
	for(;x&&!t[x].ch[c];x=t[x].fa)t[x].ch[c]=xx;
	if(!x){t[xx].fa=1;return xx;}
	int y=t[x].ch[c];
	if(t[y].len==t[x].len+1){t[xx].fa=y;return xx;}
	int yy=++cnt;t[yy]=t[y];
	t[yy].len=t[x].len+1;
	t[y].fa=t[xx].fa=yy;
	for(;x&&t[x].ch[c]==y;x=t[x].fa)t[x].ch[c]=yy;
	return xx;
}
int n;
char s[N];
vector<int>v[N<<1];
void dfs(int x){for(auto y:v[x])dfs(y),f[x]+=f[y];}
ll res;
int main(){
	scanf("%s",s),n=strlen(s);
	for(int i=0,las=1;i<n;i++)las=Add(las,s[i]-'a');
	for(int i=2;i<=cnt;i++)v[t[i].fa].push_back(i);
	dfs(1);
	for(int i=1;i<=cnt;i++)if(f[i]!=1)res=max(res,1ll*f[i]*t[i].len);
	printf("%lld\n",res);
	return 0;
}

II.【模板】广义后缀自动机(广义 SAM)

我们之前提到过一句话:“后缀自动机的构造是在线的,增量的。”而这题,便是其应用之一。

首先,有一种暴力的解法,是直接将所有东西全都依次插入SAM,每次插入从 11 开始。但是,这样插入完后,如果你输出构建的SAM,会发现有一些点是无法从根到达的!

我们重新翻出SAM的代码:

C++
int Add(int x,int c){
	int xx=++cnt;t[xx].len=t[x].len+1;
	for(;x&&!t[x].ch[c];x=t[x].fa)t[x].ch[c]=xx;
	if(!x){t[xx].fa=1;return xx;}
	int y=t[x].ch[c];
	if(t[y].len==t[x].len+1){t[xx].fa=y;return xx;}
	int yy=++cnt;t[yy]=t[y];
	t[yy].len=t[x].len+1;
	t[y].fa=t[xx].fa=yy;
	for(;x&&t[x].ch[c]==y;x=t[x].fa)t[x].ch[c]=yy;
	return xx;
}

在插入的时候,有可能发生如下一些情况:

  1. xx 已经有了 c\mathbf{c} 儿子,并且 c\mathbf{c} 儿子的 len\text{len} 刚好是 xx 自身的 len+1\text{len}+1。换句话说,该 c\mathbf{c} 儿子同 xxxx 本身是等价的。这时,如果按照上文程序模拟的话,就会发现 xxxx 成为了孤立点。解决方法即为忽略 xxxx,直接 return c\mathbf{c} 儿子即可。

  2. xx 已经有了 c\mathbf{c} 儿子,但 c\mathbf{c} 儿子不与 xxxx 等价。这时,就会发现 xxxx 未在SAM中出现,c\mathbf{c} 实际上被插到了 yyyy 位置上。

当然,尽管有着这样那样的错误,暴力插串的构建SAM方式,在大多数题中都是可以通过的!

自然,学还是要学正解的。其解决的一种方式是,只要使得任何被插入的 xx 在插入时都没有 c\mathbf{c} 儿子即可。

我们考虑一下为什么会出现有 c\mathbf{c} 儿子的情况——假如我们已经有了一个串 a,那若我们又来了一个同样的串 a,插在根节点后面,此时根节点就已经有 a 儿子了。而解决办法就是,若两个串具有相同的 LCP\text{LCP},只插入一次。也即,对所有串离线下来,建一棵trie树,然后只添加trie树上的边。

然后这又涉及到一个疑问——trie树上的边到底应该按照何种顺序加入呢?你可能会直接说“当然是dfs一遍加入啦”,但是dfs序加入就会使得我们第二次跳父亲的那重循环保证不了每条边最多只会被重定向一次,导致复杂度最多是 O(∣T∣2)O(|T|^2) 的,其中 ∣T∣|T| 是trie树中节点数。而解决方式就是采用bfs序加入。此时,就是 O(∣T∣)O(|T|) 的了。

但是,这种建trie的方式是离线的。有没有在线的方式呢?

有!只需要克服我们前面讲的两个问题就行了。

这里是正确的在线做法:

C++
int Add(int x,int c){
	if(t[x].ch[c]){
		int y=t[x].ch[c];
		if(t[y].len==t[x].len+1)return y;//(x,c) has been added into the tree already.
		int yy=++cnt;t[yy]=t[y];
		t[yy].len=t[x].len+1,t[y].fa=yy;
		for(;x&&t[x].ch[c]==y;x=t[x].fa)t[x].ch[c]=yy;
		return yy;
	}
	int xx=++cnt;t[xx].len=t[x].len+1;
	for(;x&&!t[x].ch[c];x=t[x].fa)t[x].ch[c]=xx;
	if(!x){t[xx].fa=1;return xx;}
	int y=t[x].ch[c];
	if(t[y].len==t[x].len+1){t[xx].fa=y;return xx;}
	int yy=++cnt;t[yy]=t[y];
	t[yy].len=t[x].len+1;
	t[y].fa=t[xx].fa=yy;
	for(;x&&t[x].ch[c]==y;x=t[x].fa)t[x].ch[c]=yy;
	return xx;
}

可以看到,二者唯一的差别就是第二个前面加的一坨特判。这一坨特判刚好解决了上述两个问题,应该很容易理解(毕竟,这个特判是我自己yy出来的——足以发现它有多么清晰)

无论是在线还是离线,只要是合法的做法,都不会出现孤立点、到达不了的点或是其它奇奇怪怪的东西。可以直接当作普通SAM使用。

SAM应用2:求不同子串数量

不同子串数量可以由两种思路求得。

一种是从自动机角度想,从原点出发所有路径都是子串;而因为自动机的性质,任意一条子串的路径唯一,所以只需要统计自原点出发的路径数量即可。下文中错误的解法使用的是这种思路。

另一种是从parent tree角度想。parent tree所包含的过程是不断往串开头加东西的过程,而endpos相同的串(换句话说,所有相同的子串)被归到同一个点上。这也意味着只需统计所有点上不同串的数量即可。不同串的数量,就是 max⁡−min⁡+1\max-\min+1。两种正确的解法都使用了这种思路。

错误代码(事实上可以AC):

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1001000;
int cnt=1;
struct Suffix_Automaton{int ch[26],fa,len;}t[N<<1];
int Add(int x,int c){
	int xx=++cnt;t[xx].len=t[x].len+1;
	for(;x&&!t[x].ch[c];x=t[x].fa)t[x].ch[c]=xx;
	if(!x){t[xx].fa=1;return xx;}
	int y=t[x].ch[c];
	if(t[y].len==t[x].len+1){t[xx].fa=y;return xx;}
	int yy=++cnt;t[yy]=t[y];
	t[yy].len=t[x].len+1;
	t[y].fa=t[xx].fa=yy;
	for(;x&&t[x].ch[c]==y;x=t[x].fa)t[x].ch[c]=yy;
	return xx;
}
char s[N];
int n,S,in[N<<1];
queue<int>q;
ll f[N<<1],res;
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%s",s),S=strlen(s);
		for(int j=0,las=1;j<S;j++)las=Add(las,s[j]-'a');
	}
	for(int i=1;i<=cnt;i++)for(int j=0;j<26;j++)if(t[i].ch[j])in[t[i].ch[j]]++;
	for(int i=1;i<=cnt;i++)if(!in[i])q.push(i);
	f[1]=1;
	while(!q.empty()){
		int x=q.front();q.pop();
		res+=f[x];
		for(int i=0;i<26;i++){
			if(!t[x].ch[i])continue;
			f[t[x].ch[i]]+=f[x];
			if(!--in[t[x].ch[i]])q.push(t[x].ch[i]);
		}
	}
	printf("%lld\n",res-1);
	return 0;
}

离线代码:

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1001000;
namespace TR{
	int cnt=1;
	struct Trie{int ch[26],id;}t[N];
	void Add(char *s,int n){
		int x=1;
		for(int i=0;i<n;i++){
			if(!t[x].ch[s[i]-'a'])t[x].ch[s[i]-'a']=++cnt;
			x=t[x].ch[s[i]-'a'];
		}
	}
}
namespace SAM{
	int cnt=1;
	struct Suffix_Automaton{int ch[26],fa,len;}t[N<<1];
	int Add(int x,int c){
		int xx=++cnt;t[xx].len=t[x].len+1;
		for(;x&&!t[x].ch[c];x=t[x].fa)t[x].ch[c]=xx;
		if(!x){t[xx].fa=1;return xx;}
		int y=t[x].ch[c];
		if(t[y].len==t[x].len+1){t[xx].fa=y;return xx;}
		int yy=++cnt;t[yy]=t[y];
		t[yy].len=t[x].len+1;
		t[y].fa=t[xx].fa=yy;
		for(;x&&t[x].ch[c]==y;x=t[x].fa)t[x].ch[c]=yy;
		return xx;
	}	
}
using namespace SAM;
queue<int>q;
void build(){
	q.push(1),TR::t[1].id=1;
	while(!q.empty()){
		int x=q.front();q.pop();
		for(int i=0;i<26;i++)if(TR::t[x].ch[i])TR::t[TR::t[x].ch[i]].id=Add(TR::t[x].id,i),q.push(TR::t[x].ch[i]);
	}
}
char s[N];
int n,S;
ll res;
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%s",s),S=strlen(s),TR::Add(s,S);
	build();
	for(int i=1;i<=cnt;i++)res+=t[i].len-t[t[i].fa].len;
	printf("%lld\n",res);
	return 0;
}

在线做法:

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1001000;
int cnt=1;
struct Suffix_Automaton{int ch[26],fa,len;}t[N<<1];
int Add(int x,int c){
	if(t[x].ch[c]){
		int y=t[x].ch[c];
		if(t[y].len==t[x].len+1)return y;//(x,c) has been added into the tree already.
		int yy=++cnt;t[yy]=t[y];
		t[yy].len=t[x].len+1,t[y].fa=yy;
		for(;x&&t[x].ch[c]==y;x=t[x].fa)t[x].ch[c]=yy;
		return yy;
	}
	int xx=++cnt;t[xx].len=t[x].len+1;
	for(;x&&!t[x].ch[c];x=t[x].fa)t[x].ch[c]=xx;
	if(!x){t[xx].fa=1;return xx;}
	int y=t[x].ch[c];
	if(t[y].len==t[x].len+1){t[xx].fa=y;return xx;}
	int yy=++cnt;t[yy]=t[y];
	t[yy].len=t[x].len+1;
	t[y].fa=t[xx].fa=yy;
	for(;x&&t[x].ch[c]==y;x=t[x].fa)t[x].ch[c]=yy;
	return xx;
}
char s[N];
int n,S,in[N<<1];
ll res;
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%s",s),S=strlen(s);
		for(int j=0,las=1;j<S;j++)las=Add(las,s[j]-'a');
	}
	for(int i=1;i<=cnt;i++)for(int j=0;j<26;j++)if(t[i].ch[j])in[t[i].ch[j]]++;
	for(int i=1;i<=cnt;i++)res+=t[i].len-t[t[i].fa].len;
	printf("%lld\n",res);
	return 0;
}

III.[ZJOI2015]诸神眷顾的幻想乡

假如这棵树是定根的,那么其就可以被看作一棵trie,trie上本质不同子串数可以直接被建立广义SAM解决;但是这棵树不定根,路径可能拐弯,咋办呢?

发现,其保证叶子数量 ≤20\leq20。这就意味着我们可以将以每个叶子为根所形成的trie并在一起形成一个大trie,此trie的节点数不大于 20n20n,然后对大trie跑SAM即可。时间复杂度 O(20nm)O(20nm)。

代码:

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,m;
namespace TR{//both for ordinary tree and for trie
	vector<int>v[100100];
	int cnt=1;
	int col[100100],in[100100];
	struct Trie{
		int ch[10],id;
	}t[2000100];
	void dfs(int x,int fa,int FA){
		if(!t[FA].ch[col[x]])t[FA].ch[col[x]]=++cnt;
		for(auto y:v[x])if(y!=fa)dfs(y,x,t[FA].ch[col[x]]);
	}
	void init(){
		for(int i=1;i<=n;i++)scanf("%d",&col[i]);
		for(int i=1,x,y;i<n;i++)scanf("%d%d",&x,&y),v[x].push_back(y),v[y].push_back(x),in[x]++,in[y]++;
		for(int i=1;i<=n;i++)if(in[i]==1)dfs(i,0,1);
	}
}
namespace SAM{
	int cnt=1;
	struct Suffix_Automaton{
		int ch[10],len,fa;
	}t[4000100];
	int Add(int x,int c){
		int xx=++cnt;t[xx].len=t[x].len+1;
		for(;x&&!t[x].ch[c];x=t[x].fa)t[x].ch[c]=xx;
		if(!x){t[xx].fa=1;return xx;}
		int y=t[x].ch[c];
		if(t[y].len==t[x].len+1){t[xx].fa=y;return xx;}
		int yy=++cnt;t[yy]=t[y];
		t[yy].len=t[x].len+1;
		t[xx].fa=t[y].fa=yy;
		for(;x&&t[x].ch[c]==y;x=t[x].fa)t[x].ch[c]=yy;
		return xx;
	}
	queue<int>q;
	void build(){
		q.push(1);
		TR::t[1].id=1;
		while(!q.empty()){
			int x=q.front();q.pop();
			for(int i=0;i<m;i++)if(TR::t[x].ch[i])TR::t[TR::t[x].ch[i]].id=Add(TR::t[x].id,i),q.push(TR::t[x].ch[i]);
		}
	}
}
using namespace SAM;
ll res;
int main(){
	scanf("%d%d",&n,&m);
	TR::init();
	build();
	for(int i=1;i<=cnt;i++)res+=t[i].len-t[t[i].fa].len;
	printf("%lld\n",res);
	return 0;
}

IV.[TJOI2019]甲苯先生和大中锋的字符串

判断一个子串出现几次,我们仍然可以采取之前提到的遍历parent tree的方法。

考虑一个等价类。明显,这个等价类中所有串都出现且仅出现了(等价类出现的次数)。若这个次数恰好为 kk,则从类中最长的串到最短的串,所有长度的串的数量都增加了 11。于是用一个差分数组维护这一过程,最后找到其中出现最多的长度即可。

代码:

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int T,cnt,n,m;
struct Suffix_Automaton{int ch[26],len,fa;}t[200100];
int sz[200100];
int Add(int x,int c){
	int xx=++cnt;t[xx].len=t[x].len+1;
	sz[xx]=1;
	for(;x&&!t[x].ch[c];x=t[x].fa)t[x].ch[c]=xx;
	if(!x){t[xx].fa=1;return xx;}
	int y=t[x].ch[c];
	if(t[y].len==t[x].len+1){t[xx].fa=y;return xx;}
	int yy=++cnt;t[yy]=t[y];
	t[yy].len=t[x].len+1;
	t[y].fa=t[xx].fa=yy;
	for(;x&&t[x].ch[c]==y;x=t[x].fa)t[x].ch[c]=yy;
	return xx;
}
vector<int>v[200100];
ll d[100100],mx;
void dfs(int x){for(auto y:v[x])dfs(y),sz[x]+=sz[y];}
char s[100100];
int main(){
	scanf("%d",&T);
	while(T--){
		scanf("%s%d",s,&m),n=strlen(s),cnt=1,mx=0;
		for(int i=0,las=1;i<n;i++)las=Add(las,s[i]-'a');
		for(int i=2;i<=cnt;i++)v[t[i].fa].push_back(i);
		dfs(1);
		for(int i=2;i<=cnt;i++)if(sz[i]==m)d[t[t[i].fa].len]--,d[t[i].len]++;
		for(int i=n;i;i--)d[i]+=d[i+1],mx=max(mx,d[i]);
		if(!mx)puts("-1");
		else for(int i=n;i;i--)if(d[i]==mx){printf("%d\n",i);break;}
		for(int i=1;i<=cnt;i++){memset(t[i].ch,0,sizeof(t[i].ch)),t[i].len=t[i].fa=sz[i]=0,v[i].clear();}
		for(int i=1;i<=n;i++)d[i]=0;
	}
	return 0;
} 

V.[APIO2014]回文串

具体分析详见本人的SA题解,这里主要是讲解使用SAM求子串出现次数的方法。

SAM应用3:查询一个子串的出现次数。

这个思想很简单,只需要找到该子串对应的 endpos\text{endpos} 等价类是哪个即可。

我们考虑记录 idiid_i 表示以位置 ii 结尾的后缀所对应等价类的编号。然后,假设我们要查询子串 [l,r][l,r],就找到 idrid_r,然后往上倍增地跳父亲,直到跳到长度恰好不大于 r−l+1r-l+1 的那个类,即为此子串所在的类。

使用马拉车求出所有极大回文串,复杂度 O(n(log⁡n+∣Σ∣))O\Big(n(\log n+|\Sigma|)\Big)。

代码:

C++
#include<bits/stdc++.h>
using namespace std;
const int N=300002;
typedef long long ll;
int cnt=1,ch[N<<1][26],fa[N<<1],len[N<<1],sz[N<<1];
int Add(int x,int c){
	int xx=++cnt;len[xx]=len[x]+1;
	sz[xx]=1;
	for(;x&&!ch[x][c];x=fa[x])ch[x][c]=xx;
	if(!x){fa[xx]=1;return xx;}
	int y=ch[x][c];
	if(len[y]==len[x]+1){fa[xx]=y;return xx;}
	int yy=++cnt;fa[yy]=fa[y];
	for(int i=0;i<26;i++)ch[yy][i]=ch[y][i];
	len[yy]=len[x]+1;
	fa[xx]=fa[y]=yy;
	for(;x&&ch[x][c]==y;x=fa[x])ch[x][c]=yy;
	return xx;
}
vector<int>v[N<<1];
void dfs(int x){for(auto y:v[x])dfs(y),sz[x]+=sz[y];}
int n,id[N];
ll val(int l,int r){
	l=max(l,0),r=min(r,n-1);
	int x=id[r];
	for(int i=18;i>=0;i--)if(ch[x][i]&&len[ch[x][i]]>=r-l+1)x=ch[x][i];
	return 1ll*sz[x]*(r-l+1);
}
char s[N],ss[N<<1];
int rad[N<<1];
ll res;
void Manacher(){
	int T=0,ret=0;
	ss[T++]='$';
	for(int i=0;i<n;i++)ss[T++]=s[i],ss[T++]='$';
	int Centre=-1,Rpos=-1;
	for(int i=0;i<T;i++){
		if(i<=Rpos)rad[i]=min(Rpos-i,rad[2*Centre-i]);
		while(i-rad[i]>=0&&i+rad[i]<T&&ss[i-rad[i]]==ss[i+rad[i]])rad[i]++;
		if(Rpos<i+rad[i])Centre=i,Rpos=i+rad[i];
		res=max(res,val((i-rad[i]+1)>>1,(i+rad[i]-2)>>1));
	}
}
int main(){
	scanf("%s",s),n=strlen(s);
	for(int i=0,las=1;i<n;i++)id[i]=las=Add(las,s[i]-'a');
	for(int i=1;i<=cnt;i++)ch[i][0]=fa[i],v[fa[i]].push_back(i);
	for(int j=1;j<=18;j++)for(int i=1;i<=cnt;i++)ch[i][j]=ch[ch[i][j-1]][j-1];
	dfs(1);
	Manacher();
	printf("%lld\n",res);
	return 0;
}

VI.[TJOI2015]弦论

SAM应用4:求字典序第 kk 大子串。

前面说过,自动机部分接受且仅接受原串后缀,但实际上自动机中节点都是后缀的前缀,即子串。于是在自动机上先倒着拓扑DP一下,然后正着扫一遍即可求出第 kk 大子串。而当相同子串计算多次时,我们知道一个子串的出现次数即为其所属 enspos\text{enspos} 集合中点数。于是这时DP时每条边的权值设作集合点数即可。

代码:

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int cnt=1;
struct Suffix_Automaton{
	int ch[26],fa,len;
}t[1000100];
int sz[1000100];
int Add(int x,int c){
	int xx=++cnt;t[xx].len=t[x].len+1;
	sz[xx]=1;
	for(;x&&!t[x].ch[c];x=t[x].fa)t[x].ch[c]=xx;
	if(!x){t[xx].fa=1;return xx;}
	int y=t[x].ch[c];
	if(t[y].len==t[x].len+1){t[xx].fa=y;return xx;}
	int yy=++cnt;t[yy]=t[y];
	t[yy].len=t[x].len+1;
	t[xx].fa=t[y].fa=yy;
	for(;x&&t[x].ch[c]==y;x=t[x].fa)t[x].ch[c]=yy;
	return xx;
}
int n,m,tp,in[1000100];
char s[500100];
ll f[1000100];
queue<int>q;
vector<int>v[1000100],u[1001000];
void dfs(int x){for(auto y:u[x])dfs(y),sz[x]+=sz[y];}
int main(){
	scanf("%s%d%d",s,&tp,&m),n=strlen(s);
	for(int i=0,las=1;i<n;i++)las=Add(las,s[i]-'a');
	for(int i=1;i<=cnt;i++)for(int j=0;j<26;j++)if(t[i].ch[j])v[t[i].ch[j]].push_back(i),in[i]++;
	for(int i=1;i<=cnt;i++)u[t[i].fa].push_back(i);
	dfs(1);
	for(int i=1;i<=cnt;i++)if(!in[i])q.push(i);
	while(!q.empty()){
		int x=q.front();q.pop();
		for(auto y:v[x]){
			f[y]+=f[x]+(tp?sz[x]:1);
			if(!--in[y])q.push(y);
		}
	}
	if(m>f[1]){puts("-1");return 0;}
	for(int x=1;m>0;)for(int i=0,y;i<26;i++){
		if(!(y=t[x].ch[i]))continue;
		if(m>f[y]+(tp?sz[y]:1))m-=f[y]+(tp?sz[y]:1);else{putchar('a'+i),m-=(tp?sz[y]:1),x=y;break;}		
	}
	return 0;
}

VII.[BZOJ2555]SubString

如果要在动态建SAM的过程中同时维护parent tree中的子树和,明显需要一种支持修改树的数据结构来维护。显然,这里应该使用LCT。

维护子树和,可以考虑LCT中经典的记录虚子树和的trick。然后剩下就是俩模板的拼接了。

不知道为什么,交上去会MLE(尽管空间经计算是不会爆炸的),但是与正解对拍是OK的(

MLE代码:

C++
#include<bits/stdc++.h>
using namespace std;
const int N=600100;

#define lson t[x].ch[0]
#define rson t[x].ch[1]
struct Link_Cut_Tree{int ch[2],fa,sumi,sum;bool rev;}t[N<<1];
void REV(int x){t[x].rev^=1,swap(lson,rson);}
void ADD(int x){t[x].sumi++,t[x].sum++;}
void pushup(int x){t[x].sum=t[x].sumi;if(lson)t[x].sum+=t[lson].sum;if(rson)t[x].sum+=t[rson].sum;}
void pushdown(int x){if(!t[x].rev)return;if(lson)REV(lson);if(rson)REV(rson);t[x].rev=false;}
int identify(int x){if(x==t[t[x].fa].ch[0])return 0;if(x==t[t[x].fa].ch[1])return 1;return -1;}
void rotate(int x){
	register int y=t[x].fa,z=t[y].fa,dirx=identify(x),diry=identify(y),b=t[x].ch[!dirx];
	if(diry!=-1)t[z].ch[diry]=x;t[x].fa=z;
	if(b)t[b].fa=y;t[y].ch[dirx]=b;
	t[y].fa=x,t[x].ch[!dirx]=y;
	pushup(y),pushup(x);
}
void pushall(int x){if(identify(x)!=-1)pushall(t[x].fa);pushdown(x);}
void splay(int x){for(pushall(x);identify(x)!=-1;rotate(x))if(identify(t[x].fa)!=-1)rotate(identify(x)==identify(t[x].fa)?t[x].fa:x);}
void access(int x){for(register int y=0;x;x=t[y=x].fa)splay(x),t[x].sumi+=t[rson].sum-t[y].sum,rson=y,pushup(x);}
void makeroot(int x){access(x),splay(x),REV(x);}
void split(int x,int y){makeroot(x),access(y),splay(y);}
bool link(int x,int y){split(x,y),t[x].fa=y,t[y].sumi+=t[x].sum,pushup(y);}
void cut(int x,int y){split(x,y),t[y].ch[0]=t[x].fa=0,pushup(y);}

struct Suffix_Automaton{int fa,len,ch[2];}sam[N<<1];
int cnt=1,las=1;
void Setfa(int x,int y){//set fa[x] to y.
	if(sam[x].fa)cut(x,sam[x].fa);
	sam[x].fa=y,link(x,y);
}
int Add(int x,int c){
	int xx=++cnt;sam[xx].len=sam[x].len+1;
	for(;x&&!sam[x].ch[c];x=sam[x].fa)sam[x].ch[c]=xx;
	if(!x){Setfa(xx,1);return xx;}
	int y=sam[x].ch[c];
	if(sam[y].len==sam[x].len+1){Setfa(xx,y);return xx;}
	int yy=++cnt;
	for(int i=0;i<2;i++)sam[yy].ch[i]=sam[y].ch[i];Setfa(yy,sam[y].fa),sam[yy].len=sam[x].len+1;
	Setfa(xx,yy),Setfa(y,yy);
	for(;x&&sam[x].ch[c]==y;x=sam[x].fa)sam[x].ch[c]=yy;
	return xx;
}

char s[N];
int S;
void Insert(){for(int i=0;i<S;i++)las=Add(las,s[i]-'A'),split(1,las),ADD(las);}
int Query(){
	int x=1;
	for(int i=0;i<S;i++)if(sam[x].ch[s[i]-'A'])x=sam[x].ch[s[i]-'A'];else return 0;
	split(x,sam[x].fa);
	return t[x].sum;
}

int q;
void deco(int msk){scanf("%s",s),S=strlen(s);for(int i=0;i<S;i++)msk=(msk*131+i)%S,swap(s[i],s[msk]);}
int msk;
char ord[10];
int main(){
	scanf("%d",&q);
	scanf("%s",s),S=strlen(s),Insert();
	for(int tp;q--;){
		scanf("%s",ord),tp=(ord[0]=='A'?0:1);
		deco(msk);
		if(tp)printf("%d\n",tp=Query()),msk^=tp;
		else Insert();
	}
	return 0;
}

下面我们考虑另一种思路,即把子树求和,单点加变为路径加,单点求值。路径加是LCT经典操作。

但是,我们考虑在建parent tree的过程中我们有哪些操作:

  1. 为一个节点新增儿子

明显此时该儿子的答案是 00,故直接添加即可。

  1. 在一条边中塞一个新节点

这时候,新添加的节点的答案就不是 00 了——其等于路径中深度较深的那个点当前的答案。于是我们在塞新节点的时候还要手动为它赋初值。

写带 link 和 cut 的LCT是可以的。但是,我们这里可以使用定根LCT,即不使用 makeroot 的LCT。具体而言,显然情形1就直接连父亲即可,而情形2,假设我们往边 (x,z)(x,z) 中插一个节点 yy,则我们先 access(z) 再 splay(x),这下子 xx 的右儿子就一定是 zz,此时就可以直接在中间插一个 yy 即可。明显此种做法常数更小。

代码(可以通过):

C++
#include<bits/stdc++.h>
using namespace std;
const int N=600100;

#define lson t[x].ch[0]
#define rson t[x].ch[1]
struct Link_Cut_Tree{int ch[2],fa,val,tag;}t[N<<1];
void ADD(int x,int y=1){t[x].val+=y,t[x].tag+=y;}
void pushdown(int x){if(lson)ADD(lson,t[x].tag);if(rson)ADD(rson,t[x].tag);t[x].tag=0;}
int identify(int x){if(x==t[t[x].fa].ch[0])return 0;if(x==t[t[x].fa].ch[1])return 1;return -1;}
void rotate(int x){
	register int y=t[x].fa,z=t[y].fa,dirx=identify(x),diry=identify(y),b=t[x].ch[!dirx];
	if(diry!=-1)t[z].ch[diry]=x;t[x].fa=z;
	if(b)t[b].fa=y;t[y].ch[dirx]=b;
	t[y].fa=x,t[x].ch[!dirx]=y;
}
void pushall(int x){if(identify(x)!=-1)pushall(t[x].fa);pushdown(x);}
void splay(int x){for(pushall(x);identify(x)!=-1;rotate(x))if(identify(t[x].fa)!=-1)rotate(identify(x)==identify(t[x].fa)?t[x].fa:x);}
void access(int x){for(register int y=0;x;x=t[y=x].fa)splay(x),rson=y;}
void linkson(int x,int y){t[y].fa=x;}//make y a son of x
void iterate(int x){
	if(!x)return;
	iterate(lson);
	printf("%d ",x);
	iterate(rson);
}
void expandedge(int x,int y,int z){//insert y between x and z
	access(z),splay(x);//after this step, x's rson must be z.
	t[y].fa=x,t[x].ch[1]=y;
	t[z].fa=y,t[y].ch[1]=z;//insert y between x and z
	t[y].val=t[z].val;
}

struct Suffix_Automaton{int fa,len,ch[2];}sam[N<<1];
int cnt=1,las=1;
int Add(int x,int c){
	int xx=++cnt;sam[xx].len=sam[x].len+1;
	for(;x&&!sam[x].ch[c];x=sam[x].fa)sam[x].ch[c]=xx;
	if(!x){sam[xx].fa=1,linkson(1,xx);return xx;}
	int y=sam[x].ch[c];
	if(sam[y].len==sam[x].len+1){sam[xx].fa=y,linkson(y,xx);return xx;}
	int yy=++cnt;sam[yy]=sam[y],sam[yy].len=sam[x].len+1;
	sam[xx].fa=sam[y].fa=yy;
	expandedge(sam[yy].fa,yy,y),linkson(yy,xx);
	for(;x&&sam[x].ch[c]==y;x=sam[x].fa)sam[x].ch[c]=yy;
	return xx;
}

char s[N];
int S;
void Insert(){for(int i=0;i<S;i++)las=Add(las,s[i]-'A'),access(las),splay(las),ADD(las);}
int Query(){
	int x=1;
	for(int i=0;i<S;i++)if(sam[x].ch[s[i]-'A'])x=sam[x].ch[s[i]-'A'];else return 0;
	splay(x);
	return t[x].val;
}

int q;
void deco(int msk){scanf("%s",s),S=strlen(s);for(int i=0;i<S;i++)msk=(msk*131+i)%S,swap(s[i],s[msk]);}
int msk;
char ord[10];
int main(){
	scanf("%d",&q);
	scanf("%s",s),S=strlen(s),Insert();
	for(int tp;q--;){
		scanf("%s",ord),tp=(ord[0]=='A'?0:1);
		deco(msk);
		if(tp)printf("%d\n",tp=Query()),msk^=tp;
		else Insert();
	}
	return 0;
}
原文
存档评论1 条抓取于