/*Count the string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5006 Accepted Submission(s): 2358
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.
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
Author
foreverlin@HNU
Source
HDOJ Monthly Contest – 2010.03.06
*/
#include<stdio.h>
#include<string.h>
int next[200010], dp[200010];
char s[200010];
int main()
{
int i,j, k,m, n, ans;
scanf("%d", &n);
while(n--)
{
scanf("%d%s", &m, s);
next[0] = -1;
j = -1;
i = 0;
while(i < m)//求next数组
{
if(j == -1 || s[i] == s[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
memset(dp, 0, sizeof(dp));
ans = 0;
for(i = 1; i <= m; i++)//求每一个长度的前缀种类数,并累加到ans中
{
dp[i] += dp[next[i]] + 1;
ans += dp[i];
if(ans > 10007)
ans %= 10007;
}
printf("%d\n", ans);
}
return 0;
}
题意:给定一个字符串,求长度1~自身长度的每一个子串在主串中出现的次数之和
思路:先求出字符串的next数组,可知每一位字母的最大相同前缀,从第一位开始,以dp数组存储该位之前的子串种类数,
当每判断下一位的时候,该位的dp就等于最大相同前缀的dp+1,即dp【next【i】】+1, 最后答案即为每一位的dp数之和;
难点:理解next数组中的dp转移方程
再来个好懂点的代码:
#include<stdio.h>
#include<string.h>
int next[200010], ans, n;
char s1[200010];
void getnext()
{
int i, j, k;
next[0] = -1;
i = 0;
j = -1;
while(i < n)
{
if(j == -1 || s1[i] == s1[j])
{
i++;
j++;
next[i] = j;//不采取优化不省略自身
}
else
j = next[j];
}
}
int main()
{
int i, j, k, t;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
getchar();
for(i = 0; i < n; ++i)
scanf("%c", &s1[i]);
s1[i] = '\0';
getnext();
ans = 0;
int num[200010] = {0};
for(i = 1; i <= n; ++i)
{
num[next[i]] ++;//每一个相同最大前后缀个数加1
num[next[i]] %= 10007;
}
for(i = 1; i <= n; ++i)
{
ans += num[i];//统计的相同的前后缀的个数
ans++;//加上自己
ans %= 10007;
}
printf("%d\n", ans);
}
return 0;
}