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

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
 
求解前缀数组的数目:  
代码:
 #include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
const int maxn= ;
char st[maxn];
int next[maxn];
int dp[maxn];
int main()
{
int test,lenb;
scanf("%d",&test);
while(test--)
{
scanf("%d %s",&lenb,st);
int i=,j=-;
next[]=-;
memset(dp,,sizeof(int)*(lenb+));
while(i<lenb)
{
if(j==-||st[i]==st[j])
next[++i]=++j;
else j=next[j];
}
//得到了一个next数组...
for(i=;i<=lenb;i++)
dp[i]+=dp[next[i]]+; //求解所有前缀的种类 while(next[i])
int ans=;
for(i=;i<=lenb;i++)
{
ans+=dp[i];
ans%=;
}
printf("%d\n",ans);
}
return ;
}
上一篇:[HDU 3336]Count the String[kmp][DP]


下一篇:Div里超出部分,省略号显示