Count the string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 7764 Accepted Submission(s): 3619
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.
比如例子:abab
前綴 在s中出現的次數
a 2
ab 2
aba 1
abab 1
所以結果爲6
我看到這個題目的第一反應是用循環求字符串s的每個子串next數組然後再求kmp,提交超時。(kmp算法的時間複雜度爲O(n+m),n爲字符串s的長度,m爲要求next數組的字符串的長度)
然後想了一下其實並不用求每個子串的next數組,只要求s的next數組就好了,提交還是超時。
然後想了一下s的每個子串的個數爲s的長度,然後就是和每個子串相等的個數,我想的是next數組有值的答案就要加一,提交AC。後來看杭電的 Discuss 發現杭電的數據較弱,比如abababab的答案應該爲20,但是我的代碼得出的結果是16,結果還是AC了。
<span style="font-size:18px;">#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define LL long long
using namespace std;
const int maxn = 200000+5;
int ans;
int Next[maxn];
void getNext(string s)
{
int ls=s.size();
Next[0]=-1;
Next[1]=0;
for(int i=2;i<=ls;i++){
if(s[i-1]==s[Next[i-1]]) Next[i]=Next[i-1]+1;
else{
int t=Next[i-1];
while(s[t]!=s[i-1]){
t=Next[t];
if(t==-1) break;
}
Next[i]=t+1;
}
}
}
void kmp(string a,string b)
{
int la=a.size();
int lb=b.size();
int i=0,j=0;
while(i<la && j<lb){
if(a[i]==b[j] || j==-1) i++,j++;
else{
while(a[i]!=b[j]){
j=Next[j];
if(j==-1) break;
}
}
if(j==lb) ans++,j=0;
}
}
int main()
{
cin.sync_with_stdio(false);
int t,n;
string a;
cin>>t;
while(t--){
cin>>n>>a;
ans=n;
getNext(a);
for(int i=0;i<=n;i++){
if(Next[i]>0) ans++;
}
cout<<ans%10007<<endl;
}
return 0;
}</span>