HDU - 3336 Count the string(kmp+dp)

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

题意:求这个字符串每个前缀在字符串中出现了多少次。

思路:dp[i]记录在长度为i的前缀时有多少个,递推为dp[i]=dp[Next[i]]+1,+1是因为长度为i的前缀第一次出现肯定要多一个,Next[i]表示i的前后缀匹配的长度,dp[Next[i]]表示已经出现的前缀又增加了相同的。具体看代码。


代码:

#include <cstdio>
#include <cmath>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <cctype>
#include <sstream>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int maxn = 20000 + 5;
const int mod = 10007;

//freopen ("in.txt", "r", stdin);

const int N = 200005;
int Next[N];
char S[N], T[N];
int slen, tlen;
void getNext() {
    int j, k;
    j = 0;
    k = -1;
    Next[0] = -1;
    while(j < tlen)
        if(k == -1 || T[j] == T[k])
            Next[++j] = ++k;
        else
            k = Next[k];
}
int t;
int dp[N];
int main () {
    scanf ("%d",&t);
    while (t--){
        scanf ("%d",&tlen);
        scanf ("%s",T);
        getNext();
        dp[0]=0;
        int ans=0;
        for (int i=1;i<=tlen;i++){
            dp[i]=dp[Next[i]]+1;
            dp[i]%=mod;
            ans+=dp[i];
            ans%=mod;
        }
        printf ("%d\n",ans);
    }
    return 0;
}






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值