Drink soy milk 3336 Count The string "KMP algorithm to find the total number of occurrences of the prefix in the original string"

Source: Internet
Author: User

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"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.