前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HDUOJ------3336 Count the string(kmp)

HDUOJ------3336 Count the string(kmp)

作者头像
Gxjun
发布2018-03-22 13:55:45
5640
发布2018-03-22 13:55:45
举报
文章被收录于专栏:mlml

D - Count the string

Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

Submit Status

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

1 4 abab

Sample Output

6

求解前缀数组的数目:  

代码:

代码语言:javascript
复制
 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdlib>
 4 using namespace std;
 5 const int maxn= 200050;
 6 char st[maxn];
 7 int next[maxn];
 8 int dp[maxn];
 9 int main()
10 {
11     int test,lenb;
12     scanf("%d",&test);
13     while(test--)
14     {
15       scanf("%d %s",&lenb,st);
16       int i=0,j=-1;
17       next[0]=-1;
18       memset(dp,0,sizeof(int)*(lenb+1));
19      while(i<lenb)
20      {
21        if(j==-1||st[i]==st[j])
22          next[++i]=++j;
23        else j=next[j];
24      }
25     //得到了一个next数组...
26      for(i=1;i<=lenb;i++)
27          dp[i]+=dp[next[i]]+1;  //求解所有前缀的种类  while(next[i])
28       int ans=0;
29       for(i=1;i<=lenb;i++)
30       {
31          ans+=dp[i];
32          ans%=10007;
33       }
34       printf("%d\n",ans);
35     }
36   return 0;
37 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-07-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档