HDU 3336 Count the string(KMP:串前缀匹配自身+DP)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn=200010;
const int mod=10007;
char p[maxn];
int f[maxn];
int dp[maxn];
int m;
void fail(char*p,int*f)
{
    m=strlen(p);
    f[1]=f[0]=0;
    for(int i=1;i<m;i++)
    {
        int j=f[i];
        while(j&&p[i]!=p[j])
            j=f[j];
        f[i+1]=(p[i]==p[j])?j+1:0;
    }
}
int main()
{int t;
scanf("%d",&t);
int ans;
while(t--)
{dp[0]=0;
 ans=0;
    int n;
    scanf("%d",&n);
    scanf("%s",p);
fail(p,f);
    for(int i=1;i<=n;i++)
    {
        dp[i]=dp[f[i]]+1;
        dp[i]%=mod;
        ans=(ans+dp[i])%mod;
    }
    printf("%d\n",ans);
}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sdauguanweihong/article/details/83898691