HDU 3336 kmp的应用

来源:互联网 发布:宜家沙发 知乎 编辑:程序博客网 时间:2024/05/20 20:18

Count the string

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


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


题意:给定一个字符串,求所有前缀的出现次数。

解题思路:首先求这个字符串的next数组,假如next值不为0,就代表与前面有匹配,累加,然后加上一个n,取模就得到了答案,

研究了好久,请教了好几个人才搞明白,太弱了。

代码:

/* ***********************************************Author :xianxingwuguanCreated Time :2014-2-1 22:45:04File Name :2.cpp************************************************ */#pragma comment(linker, "/STACK:102400000,102400000")#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>#include <vector>#include <queue>#include <set>#include <map>#include <string>#include <math.h>#include <stdlib.h>#include <time.h>using namespace std;const int maxn=200100;const double pi =acos(-1.0);const double eps =1e-8;const int mod=10007;char str[maxn];int next[maxn],dp[maxn];int main(){      //freopen("data.in","r",stdin);      //freopen("data.out","w",stdout);      int T,i,j,k,m,n;      cin>>T;      while(T--)      {     cin>>n;     scanf("%s",str);     j=0,k=-1;     next[0]=-1;                while(j<n)     {    if(k==-1||str[j]==str[k])   next[++j]=++k;    else k=next[k];     }     for(i=0;i<=n;i++)cout<<next[i]<<" ";cout<<endl;     for(i=0;i<n;i++)dp[i]=1;     int cnt=0;     for(i=1;i<=n;i++)if(next[i])cnt++;     cnt=(cnt+n)%mod;     cout<<cnt<<endl;      }      return 0;}


0 0
原创粉丝点击