目录:
题目:
分析:
先把题面转成人话:
对于给定串的每个前缀
,求最长的,使这个字符串重复两边能覆盖原前缀
的前缀(就是前缀i的一个前缀),求所有的这些“前缀的前缀”的长度和
利用
的性质:前缀
的长度为
的前缀和后缀是相等的
这说明:如果有
一个公共前后缀长度为
,那么这个前缀
就有一个周期为
见下图:
显然图中蓝色线段是黑色线段的一个周期
那么接下来的问题就容易了:
先求出
数组
对于每个前缀
,令
,然后在
的情况下令
,最小的
就是答案,此时
一个优化:求出
以后,令
,这样能加快递归速度(相当于记忆化了)
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<set>
#include<map>
#include<list>
#include<ctime>
#include<iomanip>
#include<string>
#include<bitset>
#define LL long long
using namespace std;
inline LL read() {
LL d=0,f=1;char s=getchar();
while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
return d*f;
}
int nex[1000001];char s[1000001];
long long ans=0;
int main()
{
int n=read();
scanf("%s",s);
nex[0]=nex[1]=0;
int j=0;
for(int i=1;i<n;i++)
{
while(j&&(s[i]!=s[j])) j=nex[j];
j+=(s[i]==s[j]);
nex[i+1]=j;
}
for(int i=1;i<=n;i++)
{
j=i;
while(nex[j]) j=nex[j];
if(nex[i]!=0) nex[i]=j;
ans+=i-j;
}
printf("%lld",ans);
return 0;
}