CF932G Palindrome Partition Sol

传送门

首先 (n) 为奇数肯定无解
(n) 为偶数时
老套路,把串 (S) 变成 (S_1S_nS_2S_{n-1}),设为 (T)
那么满足条件的 (S) 的划分相当于 (T) 中的划分,使得每一段为长度为偶数的回文串
下面就只考虑 (T) 的划分
(f_i) 表示前 (i) 个字符合法划分的方案数,用 (PAM) 可以做到 (sum) 树高
这样子远远不够
考虑 (PAM) 的一条 (parent) 链,分析其性质
(i) 为位置 (p) 在树上对应的点
(dif_i) 表示 (i) 与其中父亲的长度之差
由回文串的性质可以发现,向上会有一段的 (dif) 相同
(anc_i) 表示 (i) 上面第一个 (dif)(dif_i) 不同的祖先
容易得到 (anc_i) 的长度至多为 (i) 长度的一半
那么每次跳 (anc_i) 统计 (i)(anc_i) 的贡献就可以做到 (log)
现在考虑计算 (i)(anc_i) 的贡献
我们把父亲的串都关于儿子对称,发现恰好是以 (p-dif_i) 结尾的
在树上就是 (i) 的父亲,当然父亲必须在 (i)(anc_i) 的链上
那么
(g_i) 表示在 (i)(anc_i) 的贡献和
增量构造 (PAM) 的同时计算 (f),修改 (g)
因为要分偶数,所以奇数的 (f) 就直接去掉即可

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;

const int maxn(1e6 + 5);
const int mod(1e9 + 7);

inline void Inc(int &x, int y) {
	if ((x += y) >= mod) x -= mod;
}

int n, f[maxn], dif[maxn], anc[maxn], g[maxn];
int fa[maxn], len[maxn], trans[26][maxn], tot, last;
char s[maxn], tmp[maxn];
  
inline void Extend(int c, int pos) {
	register int np, p = last, q, i;
	while (s[pos] != s[pos - len[p] - 1]) p = fa[p];
	if (!trans[c][p]) {
		np = ++tot, len[np] = len[p] + 2, q = fa[p];
		while (s[pos] != s[pos - len[q] - 1]) q = fa[q];
		fa[np] = trans[c][q], trans[c][p] = np;
		dif[np] = len[np] - len[fa[np]];
		anc[np] = dif[np] == dif[fa[np]] ? anc[fa[np]] : fa[np];
	}
	last = trans[c][p];
}

int main() {
	register int i, j, l = 0;
	scanf(" %s", tmp + 1), n = strlen(tmp + 1);
	if (n & 1) return puts("0"), 0;
	for (i = 1, j = n; i <= j; ++i, --j) s[++l] = tmp[i], s[++l] = tmp[j];
	f[0] = 1, len[1] = -1, fa[1] = fa[0] = 1, tot = last = 1;
	for (i = 1; i <= n; ++i) {
		Extend(s[i] - 'a', i);
		for (j = last; j; j = anc[j]) {
			g[j] = f[i - len[anc[j]] - dif[j]];
            if(anc[j] != fa[j]) Inc(g[j], g[fa[j]]);
			if (~i & 1) Inc(f[i], g[j]);
		}
	}
	printf("%d
", f[n]);
	return 0;
}