ACM hdu 3336 Count the string

【题意概述】

  给定一个文本字符串,找出所有的前缀,并把他们在文本字符串中的出现次数相加,再mod10007,输出和。

【题目分析】

  利用kmp算法的next数组 再加上dp

【存在疑惑】

  在分析next数组和dp之间的关系,结论是 dp[i] = (dp[next[i]]+1); 搞不懂之间存在的联系

【AC】

 1 #include <bits/stdc++.h>
 2 
 3 int n,m,dp[300000],next[300000];
 4 
 5 char s[300000];
 6 
 7 void getnext() {
 8      int i=0,j=-1;
 9 
10      next[0]=-1;
11 
12      while(i<m) {
13 
14             if(j==-1||s[i]==s[j]) {
15                      ++i;++j;
16 
17                      next[i]=j;
18 
19             } else
20                  j=next[j];
21      }
22 }
23 
24 int main() {
25 
26     scanf("%d",&n);
27 
28     while(n--)
29     {
30               int sum=0;
31 
32               scanf("%d",&m);
33 
34               scanf("%s",s);
35 
36               getnext();
37 
38               memset(dp,0,sizeof(dp));
39 
40               for(int i=1;i<=m;++i) {
41                     dp[i]=(dp[next[i]]+1)%10007;//不理解
42                     sum=(sum+dp[i])%10007; 
43               }
44               printf("%d\n",sum);
45     }
46     return 0;
47 }

 

参考博客:https://www.cnblogs.com/yuelingzhi/archive/2011/08/03/2126346.html

posted @ 2018-04-15 10:25  听说这是最长的名字了  阅读(209)  评论(0编辑  收藏  举报