Count the string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3797 Accepted Submission(s): 1776
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数组的性质是匹配前后缀,因此,如果能匹配上那说明后缀和前缀一样,这样就能够计算前缀出现的次数。用一个cnt数组记录前后缀匹配的个数。
例如字符串abababab,当aba的前缀a和后缀a可以匹配,那么cnt[3]=1。然后abab同理可以匹配cnt[4]=1。然后是ababa此时len=3,j=5,s[len]和s[j]还是能匹配上,那么cnt[j]=cnt[len]=cnt[3]+1=2,因为如果前缀aba能匹配后缀aba,那么这个aba本身又是可以匹配前缀a和后缀a的,所以ababa当然可以匹配a,aba这两个字串,所以有以下递推式:
cnt[j]=cnt[len]+1
代码
#include <bits/stdc++.h>
using namespace std;
int nxt[200005];
int cnt[200005];
int ans;
void gettable(string s,int l){
int len=-1,j=0;
nxt[0]=-1;
while(j<l){
if(len==-1||s[j]==s[len]){
if(len!=-1){ //关键一步
cnt[j]=cnt[len]+1; //前缀相同的个数
ans+=cnt[j];
ans%=10007;
}
j++;
len++;
nxt[j]=len;
}else{
len=nxt[len];
}
}
}
int main(){
int t,l;
string s;
cin>>t;
while(t--){
ans=0;
cin>>l;
cin>>s;
gettable(s,l);
cout << (ans+l)%10007 <<endl; //子串本身也要计算
}
return 0;
}