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.
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<stdio.h>
#include<string.h>
using namespace std;
const int M=2e5+10;
char str[M];
int dp[M],next[M];
void getnext(int len)
{
next[0]=-1;
for(int i=1; i<len; i++)
{
int j=next[i-1];
while(j>=0&&str[i]!=str[j+1])
j=next[j];
if(str[i]==str[j+1])
next[i]=j+1;
else
next[i]=-1;
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
scanf("%s",str);
getnext(n);
dp[0]=1;
int sum=0;
for(int i=1; i<n; i++)
{
int j=next[i];
if(j==-1)
dp[i]=1;
else
dp[i]=dp[j]+1;
sum+=dp[i];
sum%=10007;
}
printf("%d\n",sum+1);
}
}