跳到正文

算法·理论

后缀自动机(SAM)学习笔记

AC_Lover约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前

后缀自动机,简称SAM, 字符串算法

SAM.png

一个起点,多个终点的有向无环图,原串的所有子串都和SAM起点开始的所有路径相对应

对于每个点,以其结尾的所有路径都对应一个子串,并且这些子串都是其中最长子串的连续后缀

构造过程

定义 endpos(s)\mathrm{endpos}(s) 表示子串ss在原串中出现的位置末尾编号的集合,将endpos\mathrm{endpos}相同的子串归为一个等价类

性质:

  • 对于两个子串s1,s2(∣s1∣≤∣s2∣)s_1,s_2 (|s_1|\le |s_2|),s1s_1是s2s_2的后缀当且仅当endpos(s1)⊇endpos(s2)\mathrm{endpos}(s_1)\supseteq \mathrm{endpos}(s_2),进一步地,如果有endpos(s1)=endpos(s2)\mathrm{endpos}(s_1)=\mathrm{endpos}(s_2),那么s1s_1必为s2s_2的后缀

  • 对于两个子串s1,s2(∣s1∣≤∣s2∣)s_1,s_2 (|s_1|\le |s_2|),s1s_1不是s2s_2的后缀当且仅当endpos(s1)∩endpos(s2)=∅\mathrm{endpos}(s_1)\cap\mathrm{endpos}(s_2)=\emptyset

  • 两个子串的endpos\mathrm{endpos}集合要么包含要么没有交集

  • 对于一个等价类stst,定义longest(st),shortest(st)\mathrm{longest}(st),\mathrm{shortest}(st)分别表示stst中最长和最短的串,那么

    对于任意longest(st)\mathrm{longest}(st)的后缀ss,如果满足∣shortest(st)∣≤∣s∣≤∣longest(st)∣|\mathrm{shortest}(st)|\le |s|\le |\mathrm{longest}(st)|,那么s∈sts\in st

对于一个点结尾的最长子串,其会被不同的等价类分成多个段,而每一段会用一个点来表示,这些点之间连接的就是绿边

SAM-explain.png

代码

SAM-construct.png

C++
int tot=1,lst=1;
struct Node
{
	int len,fa;
	int ch[26];
} node[N];

void extend(int c)
{
	int p=lst,np=lst=++tot;
	node[np].len=node[p].len+1;
	for (;p && !node[p].ch[c];p=node[p].fa) node[p].ch[c]=np;
	if (!p) node[np].fa=1;
	else
	{
		int q=node[p].ch[c];
		if (node[q].len==node[p].len+1) node[np].fa=q;
		else
		{
			int nq=++tot;
			node[nq]=node[q],node[nq].len=node[p].len+1;
			node[q].fa=node[np].fa=nq;
			for (;p && node[p].ch[c]==q;p=node[p].fa) node[p].ch[c]=nq;
		}
	}
}
原文