HDOJ Count the string 3336【KMP】

来源:互联网 发布:表白被拒绝怎么办知乎 编辑:程序博客网 时间:2024/06/06 09:54

Count the string

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


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   |   We have carefully selected several similar problems for you:  3746 1358 3341 2222 3068 
 


题意:

给你一个串,找出它的前缀,然后再找出它前缀在这个串里面出现几次。

解题思路:

肯定不能枚举所有前缀  跟此串比较 肯定TLE。。怎么办?肯定KMP这是毫无疑问的,但是得想到利用next数组的思想,因为每一个next数组保存的就是最长的前缀。如何判断一个前缀在串里面出现的次数?d数组表示该字符串前i个字符中,以第i个字符结尾的前缀的次数。假设我们找到截止到i位置的前缀,那么我们找到这个公共前缀的位置,让公共前缀位置上的值加1 就等于位置,递推式就是

d [ i ] = d [ next[ i ] ] + 1.

即:第i个字符结尾的前缀数等于以第next[i]个字符为结尾的前缀数加上它自己本身。

#include <stdio.h>#include <string.h>#include <algorithm>#define maxn 200000+20using namespace std;char P[maxn];int pre[maxn];void getnext(int n){pre[0]=pre[1]=0;for(int i=1;i<n;i++){int k=pre[i];while(k&&P[k]!=P[i])k=pre[k];pre[i+1]=P[i]==P[k]?k+1:0;}}int main(){int t;scanf("%d",&t);while(t--){int d[maxn];int n;scanf("%d",&n);scanf("%s",P);getnext(n);int sum=0;for(int i=1;i<=n;i++){//注意此处下标d[i]=d[pre[i]]+1;sum=(sum+d[i])%10007;}printf("%d\n",sum);}return 0;} 


0 0