原题链接: http://acm.hdu.edu.cn/showproblem.php?pid=3336
一:原题内容
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.
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.
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
二:分析理解
题意:求给定字符串含前缀的数量
abab
前缀为
a
ab
aba
abab
abab中共有六个子串是前缀a a ab ab aba abab
所以答案为6
dp[ i ]表示形如上图两红线的前缀个数。
三:AC代码
#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
#include<iostream>
#include<string.h>
using namespace std;
char p[200010];
int nextval[200010];
int dp[200010];
int p_len;
void GetNextval()
{
int i = 0, j = -1;
nextval[0] = -1;
while (i < p_len)
{
if (j == -1 || p[i] == p[j])
{
i++;
j++;
nextval[i] = j;
}
else
j = nextval[j];
}
}
int DP()
{
GetNextval();
dp[0] = 0;
int ans = 0;
for (int i = 1; i <= p_len; i++)
{
dp[i] = dp[nextval[i]] + 1;
cout << dp[i] << " ";
ans += dp[i];
ans %= 10007;
}
cout << endl;
return ans;
}
int main()
{
int N;
scanf("%d", &N);
while (N--)
{
scanf("%d", &p_len);
scanf("%s", p);
printf("%d\n", DP());
}
return 0;
}