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[j]=i,代表s[1...i]==sum[j-i+1....j],这一段其实就是前缀
i~j之间已经不可能有以j结尾的子串是前缀了,不然next【j】就不是 i 了
设dp【i】:以string[i]结尾的子串总共含前缀的数量
所以dp[j]=dp[i]+1,即以i结尾的子串中含前缀的数量加上前j个字符这一前缀
代码如下:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#define N 200010
#define M 10007
using namespace std;
int nex[N];
char a[N];
int dp[N];
int n,m,t;
void nexx(){
int j=0,k=-1;
nex[0]=-1;
while(j<t){
if(k==-1||a[j]==a[k]){
j++;k++;
nex[j]=k;
}else k=nex[k];
}
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d",&t);
scanf("%s",a);
nexx();
dp[0]=0;
int ans=0;
for(int i=1;i<=t;i++){
dp[i]=dp[nex[i]]+1;
ans=(ans+dp[i])%M;
}
printf("%d\n",ans);
}
return 0;
}
方法二:
参考大佬代码:
字符串长度为n,每一个前缀必然含1,先让sum=n;
从第二位开始遍历,一但a[i]=a[0],则遍历,相等则sum++。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#define N 200010
#define M 10007
using namespace std;
char a[N];
int main(){
int T;
scanf("%d",&T);
while(T--){
int n;
scanf("%d",&n);
scanf("%s",a);
int sum=n;
for(int i=1;i<n;i++){
if(a[i]==a[0]){
int k=0;
for(int j=i;a[j]==a[k++];j++){
sum++;
}
sum%=M;
}
}
printf("%d\n",sum);
}
return 0;
}