Description
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
Hint
题意
统计每个前缀在整个串中出现次数
题解:
设数组a[i]表示以st[i]结尾的前缀出现次数
那么有递推式 a[i] = a[nxt[i]]+1; 即长度小于i以st[i]结尾的前缀数+该子串自己(1)
AC代码
#include <cstdio>
#include <cstring>
char st[200005];
int a[200005];
int nxt[200005];
void getnext(char *s,int l){
int i = 0,j = 0;
nxt[0] = -1; j = nxt[i];
while (i<l){
if (j == -1 || s[i]==s[j]){
nxt[++i] = ++j;
}else j = nxt[j];
}
}
int main(){
int t;
scanf("%d",&t);
while (t--){
int len;
scanf("%d",&len);
scanf("%s",st);
memset(a,0,sizeof(a));
memset(nxt,0,sizeof(nxt));
getnext(st,len);
for (int i = 1;i <= len; ++i){
a[i] = a[nxt[i]]+1;
}
int sum = 0;
for (int i = 1;i <= len; ++i){
sum = (sum+a[i])%10007;
}
printf("%d\n",sum);
}
return 0;
}