http://acm.hdu.edu.cn/showproblem.php?pid=3336
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
求每一个前缀在字符串中出现的次数之和
原先其实写复杂了 不过比较好理解?
#include
using namespace std;
const int mo=10007;
int n;
char a[200005];
int nextt[200005];
int num[200005];
void get_next(){
int i=0,j=-1;
nextt[0]=-1;
while(i<=n){
if(j==-1||a[i]==a[j]){
i++;
j++;
nextt[i]=j;
}
else
j=nextt[j];
}
}
int main(){
int m,i,j,k,ans,t;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
scanf("%s",a);
get_next();
ans=1;
memset(num,0,sizeof num);
for(i=1;i
把下面缩成一块 对abcabcabc nextt[6]=3 代表a[3~5]是与a[0~2]相同 ,则就是多了一个c形成abc 贡献为dp[2]+1
#include
using namespace std;
const int mo=10007;
int n;
char a[200005];
int nextt[200005];
int dp[200005];
void get_next(){
int i=0,j=-1;
nextt[0]=-1;
while(i<=n){
if(j==-1||a[i]==a[j]){
i++;
j++;
nextt[i]=j;
}
else
j=nextt[j];
}
}
int main(){
int m,i,j,k,ans,t;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
scanf("%s",a);
get_next();
ans=0;
dp[0]=0;
for(i=1;i<=n;i++){
dp[i]=dp[nextt[i]]+1;
ans=(ans%mo+dp[i]%mo)%mo;
}
printf("%d\n",ans);
}
return 0;
}