洛谷 P3435 [POI2006]OKR-Periods of Words

目录:


题目:

传送门


分析:

先把题面转成人话:
对于给定串的每个前缀 i ,求最长的,使这个字符串重复两边能覆盖原前缀 i 的前缀(就是前缀i的一个前缀),求所有的这些“前缀的前缀”的长度和
利用 n e x t 的性质:前缀 i 的长度为 n e x t [ i ] 的前缀和后缀是相等的
这说明:如果有 i 一个公共前后缀长度为 j ,那么这个前缀 i 就有一个周期为 i j

见下图:
这里写图片描述
显然图中蓝色线段是黑色线段的一个周期
那么接下来的问题就容易了:
先求出 n e x t 数组
对于每个前缀 i ,令 j = i ,然后在 j > 0 的情况下令 j = n e x t [ j ] ,最小的 j 就是答案,此时 a n s + = i j
一个优化:求出 j 以后,令 j = f a i l [ 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;
}

猜你喜欢

转载自blog.csdn.net/qq_35786326/article/details/81783284