【KMP+DP】HDU - 3336 - Count the string

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/monochrome00/article/details/82778077

题目链接<http://acm.hdu.edu.cn/showproblem.php?pid=3336>


题意:

给出一个字符串,求出所有前缀出现次数的和。


题解:

dp[i]方程表示s[0~i-1]内后缀能匹配到的前缀个数,

因为KMP匹配到的是相同的最大后缀与最大前缀,所以可以进行转移:dp[i]=dp[nex[i]]+1

加上的1代表s[0~i-1]本身作为一个后缀和前缀匹配。


#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string.h>
#include<string>
using namespace std;
typedef long long ll;
const int N=1e6+7;
const int mod=10007;
char s[N];
int nex[N],dp[N],n;
int getnex(){
    int i=0,j=-1;
    nex[i]=-1;
    while(i<n){
        if(j==-1||s[i]==s[j]) i++,j++,nex[i]=j;
        else j=nex[j];
    }
}
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%d%s",&n,s);
        getnex();
        int ans=0;
        for(int i=1;i<=n;i++){
            dp[i]=dp[nex[i]]+1;
            ans=(ans+dp[i])%mod;
        }
        printf("%d\n",ans);
    }
}

猜你喜欢

转载自blog.csdn.net/monochrome00/article/details/82778077