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.
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.
1 4 abab
6
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 200010
using namespace std;
char s[maxn];
int ne[maxn];
int num[maxn];
void get_next()
{
int i=0,j=-1;
ne[0]=-1;
for(; s[i];)
if(j==-1||s[i]==s[j])
{
++i;
++j;
ne[i]=j;
}
else j=ne[j];
}
int main()
{
int T;
int n;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
memset(num,0,sizeof(num));
getchar();
gets(s);
get_next();
for(int i=1;i<=n;i++){
num[ne[i]]=(num[ne[i]]+1)%10007;
}
int sum=0;
for(int i=1;i<=n;i++){
if(num[i]) sum=(sum+num[i]+1)%10007;
else sum=(sum+1)%10007;
}
printf("%d\n",sum);
}
}