HDU 3336 (KMPnext数组的应用)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3336

题意:求给定字符串的前缀出现次数的总和。

题解:先求得next数组,从i=1开始遍历next数组,只要其值不为0,则让计数器加1,原因:next数组每出现不为0的时候,则代表有个一个前缀重复。

    最后再把计数器加n,原因:n个前缀没有算进去。

 

代码如下:

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 const int maxn = 200005;
 7 char s[maxn];
 8 int Next[maxn];
 9 void getNext(int len)
10 {
11     int i=0,j=-1;
12     Next[0] = -1;
13     while(i<len)
14     {
15         if(j==-1||s[i]==s[j])
16             i++,j++,Next[i] = j;
17         else
18             j = Next[j];
19     }
20 }
21 int main()
22 {
23     int test;
24     cin>>test;
25     while(test--)
26     {
27         int n;
28         scanf("%d%s",&n,s);
29         getNext(n);
30         int sum=0;
31         for(int i = 0;i<=n;i++)
32         {
33             if(Next[i]&&i)
34                 sum++;
35             if(sum>10007)
36                 sum=sum%10007;
37         }
38         sum+=n;
39         sum=sum%10007;
40         cout<<sum<<endl;
41     }
42 }
View Code

 

posted on 2015-07-16 16:24  小松song  阅读(134)  评论(0)    收藏  举报

导航