hdu 3336 Count the string(扩展KMP模板)

来源:互联网 发布:建站宝盒 源码 编辑:程序博客网 时间:2024/06/05 17:49

Count the string

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


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
 
题意:求所给字符串中的子串是字符串前缀的次数,,样例 abab的前缀 a,ab,aba,abab.子串 a,b,a,b,ab,ba,ab,aba,bab,abab所以是6分析可以发现就是求原串每一个下标与本身的最长公共前缀之和,裸扩展KMP#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#define MOD 10007using namespace std;char s[200010],str[200010];int next[200010],extend[200010];int EKMP(int len){    int ans=0,k=1,leng,l,j=0;    next[0]=0;    while(j<len&&s[j]==s[j+1])        j++;    next[1]=j;    for(int i=2;i<len;i++)    {        leng=next[k]+k-1;        l=next[i-k];        if(l+i-1<leng)            next[i]=l;        else        {            j=max(0,leng-i+1);            while(i+j<len&&s[i+j]==s[j])                j++;            next[i]=j;            k=i;        }    }    j=0,k=0;    while(j<len&&str[j]==s[j])        j++;    extend[0]=j;    ans=(ans+extend[0])%MOD;    for(int i=1;i<len;i++)    {        leng=extend[k]+k-1;        l=next[i-k];        if(l+i-1<leng)        {            extend[i]=l;        }        else        {            j=max(0,leng-i+1);            while(i+j<len&&str[i+j]==s[j])                j++;            extend[i]=j;            k=i;        }        ans=(ans+extend[i])%MOD;    }    return ans;}int main(){    int T,n;    cin>>T;    while(T--)    {        cin>>n;        scanf("%s",s);        strcpy(str,s);        cout<<EKMP(n)<<endl;    }    return 0;}


0 0
原创粉丝点击