求每一个前缀在整个传中出现过多少次
Count the string
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 18 Accepted Submission(s) : 11
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.
1 4 abab
6
#include <stdio.h>
#include <string.h>
int next[200006],sum,m;
char t[200006];
void getnext()
{
int i,j;
i=0,j=-1,next[0]=-1;
while(i<m)
{
if(j==-1||t[i]==t[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int main()
{
int n,i,j;
scanf("%d",&n);
while(n--)
{
memset(next,0,sizeof(next));
scanf("%d%s",&m,t);
sum=m;
getnext();
for(j=1; j<m; j++)
{
if(t[0]==t[j])
sum++;
}
for(j=1; j<=m; j++)
{
if(next[j]>1)
{
sum++;
sum%=10007;
}
}
printf("%d\n",sum);
}
}