Count the string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3002 Accepted Submission(s): 1397
Problem DescriptionIt 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.
InputThe 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.
OutputFor 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
Authorforeverlin@HNU
SourceHDOJ Monthly Contest – 2010.03.06
Recommendlcy 這個題目好像有點歧義,不過不要想太多,直接在next值上作文章就OK 了這個next值記錄的就是當前位置向前 多少個和這個字串開頭多少個相等有了這樣我們只要記錄每個next值對應有多少個,然後加上n個自身的一個匹配就OK 了!這個題目的關鍵還是對KMP的理解,本質上kmp的next就是表示串內關係的一個值,理解KMP是理解AC自動機的基礎
#include <iostream>#include <string.h>#include <stdio.h>using namespace std;char str[200001];int next[200001];int rec[200001];int n;int get_next(){int i=0,j=-1;next[0]=-1;while(str[i]){if(j==-1 || str[i]==str[j]){i++;j++;next[i]=j;}elsej=next[j];}return 0;}int main(){int t,i,j;int ans;scanf("%d",&t);while(t--){ans=0;scanf("%d",&n);scanf("%s",str);memset(rec,0,sizeof(rec));str[n]='a';str[n+1]=0;get_next();for(i=1;i<=n;i++)rec[next[i]]++;for(i=1;i<=n;i++)if(rec[i] > 0){ans+=rec[i];ans%=10007;}ans+=n;printf("%d\n",ans%10007);}return 0;}