It is well known that AekdyCoin is good at string problems as well as number theory problems. When given a string s, we can write down all the non-empty prefixes of this string. For example:
s: "abab"
The prefixes are: "a", "ab", "aba", "abab"
For each prefix, we can count the times it matches in s. So we can see that prefix "a" matches twice, "ab" matches twice too, "aba" matches once, and "abab" matches once. Now you are asked to calculate the sum of the match times for all the prefixes. For "abab", it is 2 + 2 + 1 + 1 = 6.
The answer may be very large, so output the answer mod 10007.
Input
The first line is a single integer T, indicating the number of test cases.
For each case, the first line is an integer n (1 <= n <= 200000), which is the length of string s. A line follows giving the string s. The characters in the strings are all lower-case letters.
Output
For each case, output only one number: the sum of the match times for all the prefixes of s mod 10007.
Sample Input
1
4
abab
Sample Output
6
这次的KMP求的前面的一个数的总和,前面出现过几次,用一个递推关系即可,如果出现过,就加上前面出现的次数,没出现过的话,就赋值为1,以此递推。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int mod = 10007;
const int maxN = 2e5 + 7;
int N, nex[maxN];
char s[maxN];
ll ans, dp[maxN];
void cal_nex()
{
memset(dp, 0, sizeof(dp));
nex[0] = nex[1] = 0;
dp[1] = 1;
ans = 1;
int k = 0;
for(int i=2; i<=N; i++)
{
while(k>0 && s[k+1] != s[i]) k = nex[k];
if(s[k+1] == s[i]) k++;
nex[i] = k;
dp[i] = 1;
if(k) dp[i] += dp[k];
ans = (ans + dp[i])%mod;
}
}
int main()
{
int T; scanf("%d", &T);
while(T--)
{
scanf("%d", &N);
scanf("%s", s + 1);
cal_nex();
printf("%lld\n", ans);
}
return 0;
}