求一个串所有前缀出现次数的和。
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;
}