hdu 3336 count the string(KMP+dp)

题意:

求给定字符串,包含的其前缀的数量。

分析:

就是求所有前缀在字符串出现的次数的和,可以用KMP的性质,以j结尾的串包含的串的数量,就是next[j]结尾串包含前缀的数量再加上自身是前缀,dp[i]表示以i为结尾包含前缀的数量,则dp[i]=dp[next[i]]+1,最后求和即可。

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <cstdio>
#include <vector>
#include <string>
#include <cctype>
#include <complex>
#include <cassert>
#include <utility>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int,int> PII;
typedef long long ll;
#define lson l,m,rt<<1
#define pi acos(-1.0)
#define rson m+1,r,rt<<11
#define All 1,N,1
#define read freopen("in.txt", "r", stdin)
#define N 200010
const ll  INFll = 0x3f3f3f3f3f3f3f3fLL;
const int INF= 0x7ffffff;
const int mod =  10007;
int dp[N],f[N],n;
char str[N];
void getnext(){
    int i=0,j=-1;
    f[0]=-1;
    while(i<n){
        if(j==-1||str[i]==str[j])
        {
            i++;j++;
            f[i]=j;
        }
        else j=f[j];
    }
}
void solve(){
    getnext();
        //cout<<1<<endl;
    memset(dp,0,sizeof(dp));
    int total=0;
    for(int i=1;i<=n;++i){
        dp[i]=(dp[f[i]]+1)%mod;
        total=(total+dp[i])%mod;
    }
    printf("%d\n",total);
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        scanf("%s",str);
        solve();
    }
return 0;
}

 

转载于:https://www.cnblogs.com/zsf123/p/4780766.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值