hdu -- 3336 Count the string(KMP + dp)

13 篇文章 0 订阅
1 篇文章 0 订阅

求一个串所有前缀出现次数的和。

http://acm.hdu.edu.cn/showproblem.php?pid=3336

首先KMP得到next数组。dp[i]表示以i结尾的串的个数。

//#pragma comment(linker,"/STACK:1024000000,1024000000")
#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

typedef long long ll;
typedef pair<int, int> PII;

#define pb push_back
#define MP make_pair
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1

const double eps = 1e-6;
const int inf = 0x3f3f3f3f;
const int mod = 10007;
const int maxn = 200000 + 10;


char str[maxn];
int next[maxn], dp[maxn], n, T;//dp[i]=以i结束的串的前缀和
void preKMP(){
    next[0] = 0;
    int j = 0;
    for(int i=2; i<=n; i++){
        while(j != 0 && str[i] != str[j + 1]) j = next[j];
        if(str[i] == str[j + 1]) j++;
        next[i] = j;
    }
}
int main(){
    scanf("%d", &T);
    while(T--){
        scanf("%d", &n);
        scanf("%s", str + 1);
        preKMP();
        dp[0] = 0;
        int ans = 0;
        for(int i=1; i<=n; i++){
            dp[i] = (dp[next[i]] + 1) % mod;//以i结尾的串一定包含了以next[i]结尾的所有子串,再加上长度为i的串
//            cout << dp[i] << " " << next[i] << endl;
            ans = (ans + dp[i]) % mod;
        }
        printf("%d\n", ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值