K - Count the string
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.
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.
OutputFor each case, output only one number: the sum of the match times for all the prefixes of s mod 10007. Sample Input
1 4 ababSample Output
6
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
const int maxlen = 1000100;
int n;
int m;
int arrnext[maxlen+1];
int res[maxlen + 1];
char mai[maxlen];
char sub[maxlen];
void getnext()
{
int i = 0;
int j = -1;
arrnext[0] = -1;
int len = strlen(sub);
while (i <= len)
{
if (j == -1 || sub[i] == sub[j])
{
j++;
i++;
arrnext[i] = j;
//if (i-arrnext[i] != i&&i%(i-arrnext[i]) == 0)
//{
// printf("%d %d\n", i, i / (i - arrnext[i]));
//}
}
else
j = arrnext[j];
}
//printf("%d\n",len%(len - arrnext[len])==0?len/(len - arrnext[len]):1);
}
void kmp()
{
getnext();
int ans = 0;
int i = 0;
int j = 0;
int lenmai = strlen(mai);
int lensub = strlen(sub);
while (i < lenmai)
{
while (i < lenmai&&j < lensub)
{
if (j == -1 || mai[i] == sub[j])
{
i++;
j++;
}
else
j = arrnext[j];
}
if (j == lensub)
{
j = 0;
ans++;
}
}//while
printf("%d\n", ans);
}
int t;
int main()
{
scanf("%d", &t);
int key = 0;
while (t--)
{
int x;
scanf("%d", &x);
//if (x == 0)
// break;
key++;
//scanf("%s",mai);
scanf("%s", sub);
//if (sub[0] == '.')
//break;
//printf("Test case #%d\n", key);
//kmp();
getnext();
//printf("\n");
int lensub = strlen(sub);
//int ans = lensub - arrnext[lensub];
//printf("%d\n", lensub%ans == 0 ? (lensub == ans ? ans : 0) : ans - (lensub%ans));
int ans = 0;
res[0] = 0;
for (int i = 1;i <= lensub;i++)
{
res[i] = 1 + res[arrnext[i]];
res[i] %= 10007;
ans += res[i];
ans %= 10007;
}
printf("%d\n", ans);
}
return 0;
}