Count the string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 12784 Accepted Submission(s): 5899
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
next 数组 存放的是 [1 ,i-1] 上最大前后缀相等的长度
如果不为0 呢吗 这个字传一定是出现了两次
如果为0 在 1~i-1 只出现了 一次
#include<iostream>
#include<stdio.h>
#include<string>
#include<stdlib.h>
#include<string.h>
using namespace std;
int nxt[200007];//存放最长前后缀公共的长度
string p,str;//模式串 主串
char ch[200007];
void GetNxt(int len)
{
nxt[0] = nxt[1] = 0;
for(int i = 1;i<len;i++)
{
int j = nxt[i];//nxt[i] 代表当前1~i的子串中 最大前后缀的长度为 nxt[i]
while(j && ch[i] != ch[j]) j = nxt[j];//没有匹配成功 呢么就一直往前找
if(ch[i] == ch[j])
nxt[i+1] = j+1;
else
nxt[i+1] = 0;
}
}
int main()
{
ios::sync_with_stdio(false);
int ncase;
scanf("%d",&ncase);
while(ncase--)
{
int len;
scanf("%d %s",&len,ch);
GetNxt(len);
int num =0;
/*
nxt[0] = 0; 代表 abab 的次数
nxt[1] = 0; 代表 a
nxt[2] = 0; 代表 ab 次数 :
nxt[3] = 1; 代表 a的出现的 次数 : 2
nxt[4] = 2; 代表ab 出现的次数 1
*/
for(int i = 0;i<len;i++)
{
if(nxt[i]) num = (num + 2) %10007;//这里是由于 nxt 数组的特性所决定的 只要 nxt[i] 不为0 呢吗 在 前 1 ~i-1 中 就一定出现了两次
else
num = (num + 1 )%10007;//最长前后缀的长度 为0 呢吗 这个子串在 前 1~ i-1 出现了 一次
}
if(nxt[len]) num = (num + 1) %10007;//如果最后一个nxt值不为0 那么说明 在前 n 个元素 的最
printf("%d\n",num %10007 );
}
return 0;
}