Count the string
Time limit:2000/1000 MS (java/others) Memory limit:32768/32768 K (java/others)
Total submission (s): 6062 Accepted Submission (s): 2810
Problem DescriptionIt is well known the 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 is: "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 is asked to calculate the sum of the match times for all the prefixes. For "Abab", it is 2 + 2 + 1 + 1 = 6.
The answer is very large, so output the answer mod 10007.
Inputthe first line was a single integer T, indicating the number of test cases.
For each case, the first line was an integer n (1 <= n <= 200000), and which is the length of the string s. A line follows giving the string s. The characters in the strings is all lower-case letters.
Outputfor each case, output only one number:the sum of the match times for all the prefixes of S mod 10007.
Sample INPUT1 4 Abab
Sample OUTPUT6
#include <stdio.h> #include <string.h> #define MOD 10007#define MAX 200010char p[max];int f[max];int Dp[max]; void Getfail () {int i,j;f[0]=f[1]=0;int len=strlen (p); for (i=1;i<len;i++) {j=f[i];while (j&&p[i]!=p[j]) j=f [J];f[i+1]=p[i]==p[j]?j+1:0;}} int main () {int n,m,j,i,s,t;scanf ("%d", &t), while (t--) {scanf ("%d", &n), scanf ("%s", p); Getfail (); s=0;dp[0]=0; for (i=1;i<=n;i++) {dp[i]= (dp[f[i]]%mod+1)%mod;s= (S%mod+dp[i]%mod)%mod;} printf ("%d\n", s);} return 0;}
Drink soy milk 3336 Count The string "KMP algorithm to find the total number of occurrences of the prefix in the original string"