Count the string
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 5 Accepted Submission(s) : 2
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
Sample Output
这个题是简单的KMP算法,每个前缀自已不算有N次,如果状态转移非0,则存在最大匹配子串(即与前缀相等),所以所有next[i] != 0的加上N,就是最后的结果。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
int next[200005];
char s[200005];
int res;
int n ;
void get_next()
{
int j ;
res = 0;
next[0]=next[1]= 0;
for(int i = 1; i < n; i ++)
{
j = next[i];
while(j && s[j] != s[i]) j = next[j];
next[i+1] = s[i] == s[j] ? j + 1: 0;
if(next[i+1])
{
res ++;
res %= 10007;
}
}
res += n;
printf("%d\n",res%10007);
}
int main()
{
int t ;
scanf("%d",&t);
while(t --)
{
scanf("%d",&n);
scanf("%s",s);
get_next();
}
return 0;
}
Count the string,布布扣,bubuko.com
Count the string
原文:http://blog.csdn.net/wuhuajunbao/article/details/22958773