【字符匹配专题】--1004 NEXT

来源:互联网 发布:mac打不开dmg文件 编辑:程序博客网 时间:2024/06/14 01:41

Count the string

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 11   Accepted Submission(s) : 5
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
 



这个题主要是关于NEXT数组的应用...



#include <iostream>#include <string.h>using namespace std;int next[1000000];int a[1000000];string s;void get_next(string t){int i,j;i=0;next[0]=-1;j=-1;while(i<t.size()){if(j==-1||t[i]==t[j]){i++;j++;//if(t[i-1]!=t[j-1])next[i]=j;//else//next[i]=next[j];}elsej=next[j];}}int main(){int n,len;cin>>n;while(n--){cin>>len;cin>>s;get_next(s);int ans=0;memset(a,0,sizeof(a));for(int i=1;i<=len;i++){a[i]=(a[next[i]]+1)%10007;ans=(ans+a[i])%10007;}//for(int i=1;i<=len;i++)cout<<ans<<endl;}return 0;}


原创粉丝点击