PAM好题QAQ
我们先把题目要求转化成回文串,假设分成了 段为 ,我们单独看 和 ,假设他们的长度是 ,那么对于原串 就有:
于是我们构造一个串 ,这样子我们求长度为偶数且总和为 的回文串方案数就可以了。
然后我们考虑dp,设 表示以 结尾的方案数,那么就有 ,其中 于是我们一直跳 就可以得到所有的 。
但是这样子做过不去的,全是相同字符就会退化到 ,于是我们再进一步考虑。
对于字符串 有:一个字符串的所有 会形成 个不相交的等差数列。
考虑证明,我们对于比 大的两个 ,假设 是该串的最长 ,那么 是其最小周期,那么 ,于是对于所有满足 的都是字符串的 ,然后递归考虑 的问题就可以了。
那么对于回文串,我们显然有如果一个串 的后缀 是回文的,那么 是 的 ,于是我们通过这个来优化复杂度。
设 表示以 这个结点结束的等差数列的贡献,具体点就是如果这段等差数列长度分别为 ,那么 , 是当前位置。
于是我们考虑求这个东西,根据回文串的性质,发现 ,因为 会把 之前的都算到,然后加上自己的贡献就可以了,这样子复杂度就变成了
Code
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
const int N = 1e6;
const int mod = 1e9 + 7;
using namespace std;
int n;
char s[N + 5],ns[N + 5];
struct PAM
{
int ch[N + 5][26],fail[N + 5],len[N + 5],nc,las,f[N + 5],sf[N + 5],d[N + 5],pos[N + 5];
char s[N + 5];
void init(char *ch)
{
for (int i = 1;i <= n;i++)
s[i] = ch[i];
s[0] = '#';
len[1] = -1;
pos[0] = 1;
fail[0] = 1;
f[0] = 1;
nc = 1;
}
void insert(int x)
{
int p = las;
while (s[x - len[p] - 1] != s[x])
p = fail[p];
if (!ch[p][s[x] - 'a'])
{
len[++nc] = len[p] + 2;
int j = fail[p];
while (s[x - len[j] - 1] != s[x])
j = fail[j];
fail[nc] = ch[j][s[x] - 'a'];
d[nc] = len[nc] - len[fail[nc]];
if (d[nc] == d[fail[nc]])
pos[nc] = pos[fail[nc]];
else
pos[nc] = fail[nc];
ch[p][s[x] - 'a'] = nc;
}
las = ch[p][s[x] - 'a'];
int j = las;
while (j > 1)
{
sf[j] = f[x - len[pos[j]] - d[j]];
if (pos[j] != fail[j])
sf[j] += sf[fail[j]],sf[j] %= mod;
if (x % 2 == 0)
f[x] += sf[j],f[x] %= mod;
j = pos[j];
}
}
void build()
{
for (int i = 1;i <= n;i++)
insert(i);
}
}pa;
int main()
{
scanf("%s",s + 1);
n = strlen(s + 1);
int l = 1,r = n;
for (int i = 1;i <= n;i++)
if (i % 2 == 1)
ns[i] = s[l++];
else
ns[i] = s[r--];
pa.init(ns);pa.build();
cout<<pa.f[n]<<endl;
return 0;
}