P10475 KMP Hash

先考虑一维的情况。

如果字符串 \(s\)\(k ~ (k \mid s)\) 个子串 \(t\) 首尾拼接而成,则 \(s\)\(t\) 的循环之一。

在已知 \(s\) 的情况下,定义 长度最小\(t\)\(t_{\min}\)

由于 \(s\)\(t_{\min}\) 的循环,其前缀函数值有 特殊的规律

易证,\(\forall |t_{\min}| \leq i \leq |s| - 1\),有 \(\pi_i = i - |t_{\min}| + 1\)。以 \(\texttt{abaabaaba}\) 为例,

\[\small \begin{matrix} i &0 &1 &2 &3 &4 &5 &6 &7 &8 \\ s_i &\texttt a &\texttt b &\texttt a &\texttt a &\texttt b &\texttt a &\texttt a &\texttt b &\texttt a \\ \pi_i &0 &0 &1 &\color{red} 1 &\color{red} 2 &\color{red} 3 &\color{red} 4 &\color{red} 5 &\color{red} 6 \end{matrix} \]

可以看到,

\[\pi_{|s| - 1} = |s| - |t_{\min}| \]

\[|t_{\min}| = |s| - \pi_{|s| - 1} \]

在二维的情况下,将列或行的 Hash 值数组当作要处理的字符串,计算其前缀函数。令每行 Hash 的前缀函数为 \(\pi\),每列的前缀函数为 \(\pi'\),则答案为 \((m - \pi_{m - 1})(n - \pi'_{n - 1})\)

posted @ 2024-07-12 14:04  Carrot-Meow~  阅读(14)  评论(0)    收藏  举报