PAM 笔记
缪凌锴_Mathew
·
·
算法·理论
PAM
\gdef\fail{\operatorname{fail}}
约定:最长回文前后缀为最长回文严格前后缀。
基础结构
- 结构:两棵回文树,存储长度是奇数、偶数的回文串。初始奇根 len=-1,偶根 len=0。
- 状态:对应一个回文串。
- 转移边:转移 c 表示前后各添加一个 c。
-
增量构造
记终止状态 lst 为当前的最长回文后缀。
新添加一个 s_p=c,在 lst 开始跳 \fail 直到匹配 c,记跳到了 x。
走转移边 x\xrightarrow{c}y,不存在则新建节点 y,并找出 \fail_y。
找 \fail_y:从 y 继续跳 \fail 直到匹配 c(跳到偶根停下),记跳到 z\xrightarrow{c}w,\fail_y=w。
可以看出很像 AC 自动机。
用深度均摊,时间复杂度 O(n)。
线性状态数证明
::::info[定理]{open}
对于一个字符串 s,它的本质不同回文子串个数最多只有 |s| 个。
::::
::::success[证明]{open}
新增一个字符后,最长的回文后缀为 o,所有除 o 外的回文后缀都可以用 o 对称回原串内。
代码实现
namespace PAM{
int idx=2,lst=2;
int fat[MAXN],len[MAXN];
int to[MAXN][26];
inline void bld(){
len[1]=-1;
len[2]=0;
fat[2]=1;
for(int i=1;i<=n;i++)
{
auto find=[&](int x){
while(x^1&&s[i-len[x]-1]^s[i])
{
x=fat[x];
}
return x;
};
int x=find(lst),c=s[i]-'a';
if(!to[x][c]){
int y=++idx;
fat[y]=x>1?to[find(fat[x])][c]:2;
len[y]=len[x]+2;
to[x][c]=y;
}
lst=to[x][c];
}
}
}
例题
P5496 【模板】回文树 / 回文自动机(PAM)
以 i 结尾的回文串数量即 s[1,i] 的 PAM 的 \fail 树上 lst 的深度。
Submission
P5555 秩序魔咒
建出两个串的 PAM,然后枚举两个串的所有回文子串。
实现上,从两个串的奇根或偶根开始 dfs,每次两边同时走同一个字符的转移边。
Submission
回文 Border 理论
\gdef\bd{\operatorname{border}}
::::info[定理 1]{open}
回文串的回文前后缀与其 \bd 对应。
::::
::::success[证明]{open}
对于 s 的一个回文前后缀 t,s 的另一侧是 rev(t),t=rev(t),故 t 为 \bd。
| 对于 s 的一个 \bd t,t=rev(t),t 是回文前后缀。 |
::::info[推论]{open}
::::
::::success[证明]{open}
回文后缀对应 $\bd$,故同 $\bd$ 理论。
::::
::::info[定理 2]{open}
回文串 $s$ 的最长回文前后缀 $t$,若 $2|t|\ge |s|$,$t$ 只在 $s$ 中出现两次(分别作为前后缀)。
::::
::::success[证明]{open}
假设 $t$ 第二次出现不是后缀:
$$
\begin{aligned}
&\boxed{\rule[-2px]{}{9px}\qquad\ \ t\qquad\ \ \ }\\
&\qquad\quad\quad\ \ \boxed{\rule[-2px]{}{9px}\qquad\ \ t\qquad\ \ \ }
\end{aligned}
$$
$$
\begin{aligned}
\boxed{\rule[-2px]{}{9px}\ x\ }\boxed{\rule[-2px]{}{9px}\quad y\quad}&\boxed{\rule[-2px]{}{9px}\ x\ }\\
&\boxed{\rule[-2px]{}{9px}\ x\ }\boxed{\rule[-2px]{}{9px}\quad y\quad}\boxed{\rule[-2px]{}{9px}\ x\ }
\end{aligned}
$$
那么 $xyxyx$ 组成比 $t$ 更长的回文前缀,与最长回文前缀矛盾。
::::
对于一个划分出的等差数列 $a_{1\sim k}$,若存在 $2a_i< a_{i+1}$,再划分为 $a_{1\sim i}$ 和 $a_{i+1\sim k}$ 两个等差数列。
容易发现这样还是 $O(\log n)$ 个等差数列,并且相邻两个后缀满足定理 2。
## 例题
### [P14185 回文子串划分计数](https://www.luogu.com.cn/problem/P14185)
设 $f_i$ 表示 $s[1,i]$ 的划分方案数。
暴力在 PAM 上跳是 $O(n^2)$ 的。
考虑推论,$s[1,i]$ 的回文后缀是若干段等差数列。
### [CF932G Palindrome Partition](https://www.luogu.com.cn/problem/CF932G)
构造 $S'=S_nS_1S_{n-1}S_2\dots$,问题等价于把 $S'$ 划分成若干偶回文串。