hdu3336(KMP)

来源:互联网 发布:网页设计需要美工吗 编辑:程序博客网 时间:2024/05/22 17:36

Count the string

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3245    Accepted Submission(s): 1513


Problem 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
14abab
 

Sample Output
6
 

Author
foreverlin@HNU
 

Source
HDOJ Monthly Contest – 2010.03.06
 

Recommend
lcy
 
本题要求所给字符串的前缀在整个字符串中出现的次数的累加和。KMP算法的运用。
容易联想到KMP算法中的next[]数组,当next[i]>0时可以理解为i前面的next[]个字符组成的字符串对应一个前缀。此外长度为n的字符串有n个前缀。
#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int MAXN= 200000+100;const int mod=10007;int next[MAXN];char str[MAXN];void getNext(char *p){    int j,k;    j=0;    k=-1;    int len=strlen(p);    next[0]=-1;    while(j<len)    {        if(k==-1||p[j]==p[k])        {            j++;            k++;            next[j]=k;        }        else k=next[k];    }}int main(){int cas,n,i,ans;cin>>cas;while(cas--){scanf("%d",&n);scanf("%s",str);getNext(str);ans=n;for(i=0;i<=n;i++){if(next[i]>0)ans+=1;ans%=mod;}printf("%d\n",ans);}return 0;}