HDU 3336 Count the string【EXKMP+逆向思考 OR KMP】

来源:互联网 发布:服务器软件架构 编辑:程序博客网 时间:2024/06/06 01:30

Count the string

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


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

题意:求一个串以第一位开头的所有前缀在原串中含有的数量之和;

思路:问题是求前缀形成的模式串与原串进行匹配,看原串中含有多少个模式串,如果枚举每一个前缀然后用KMP来匹配,时间复杂度为O(N*N),所以这种方法不行,注意到求每一个前缀在与原串的子串匹配个数,可以反过来求,枚举每一个原串的子串然后计算与所有前缀的匹配的个数,这个就可以借助EXKMP的next来计算了:next[i]=j  表示原串i位的后缀与原串匹配的最长长度,就表示与下标为0的前缀长度为1,2......j的都匹配,匹配个数就是next[i],将所有的next求和就是结果了;

失误:EXKMP理解不深刻,模板记得还不熟,夜里怎么检查检查不出来,第二天一眼看出来了;


AC代码:

#include<cstdio>#include<algorithm>using namespace std;#define mod 10007const int MAXN=2*1e5+22;char str[MAXN]; int ne[MAXN];void Get_Ene(char T[],int ne[],int L){ne[0]=L; int i=0;while(i+1<L&&T[i]==T[i+1]) ++i;ne[1]=i;  int id=1;for(i=2;i<L;++i){int mx=id+ne[id]-1,ll=ne[i-id];if(i+ll-1>=mx){int j=max(0,mx-i+1);while(i+j<L&&T[j]==T[i+j]) ++j;ne[i]=j; id=i;}else ne[i]=ll;}}int main(){int T,N,i;scanf("%d",&T);while(T--){scanf("%d %s",&N,str);Get_Ene(str,ne,N);int ans=0;for(i=0;i<N;++i){   ans+=ne[i];   ans%=mod;}printf("%d\n",ans);  } return 0; } 


      下面的KMP方法看宇神DP的没看懂 到网上找了一篇很好:主要是next【i】=j 表示0-(i-1)的字符串的最大前后缀长度为j也就是对答案的贡献是j  不过我不知道再怎样去除重复加的 讲解:http://972169909-qq-com.iteye.com/blog/1114968   


KMP:

#include<cstdio>#define MOD 10007const int MAXN=2*1e5+33;char str[MAXN]; int ne[MAXN];void Get_ne(char *T,int *ne,int L){ne[0]=-1;int i=0,j=-1;while(i<L){if(j<0||T[i]==T[j]) ne[++i]=++j;else j=ne[j];}}int main(){int T,N,i;scanf("%d",&T);while(T--){scanf("%d %s",&N,str);Get_ne(str,ne,N);int ans=N;for(i=1;i<N;++i){if(ne[i]>0&&ne[i]+1!=ne[i+1]) ans=(ans+ne[i])%MOD;  }  printf("%d\n",ans); }return 0; } 


0 0