题目链接
题意:给一个长度为n的字符串,求每个前缀在字符串中的出现次数的和,答案模10007。
分析:kmp水题,按顺序遍历每个前缀,当前缀出现的次数为1,后面肯定都为1。
#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
#define PI acos(-1)
const double eps=1e-6;
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int mod=10007;
const int maxn=2e5+10;
int nx[maxn];
void getnx(string x){
int m=x.size();
int i,j;
j=nx[0]=-1;
i=0;
while (i<m){
while (-1!=j && x[i]!=x[j]) j=nx[j];
if (x[++i]==x[++j]) nx[i]=nx[j];
else nx[i]=j;
}
}
int kmp_count(string s, string t){
int n=s.size();
int m=t.size();
int i=0,j=0,ans=0;
getnx(t);
while (i<n){
while (-1!=j && s[i]!=t[j]) j=nx[j];
i++;
j++;
if (j>=m){
ans++;
j=nx[j]; //如果不可重叠,将此处改为 j=0;
}
}
return ans;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin>>T;
while (T--){
int n;
cin>>n;
string s;
cin>>s;
ll ans=0;
//getnx(s);
for (int i=1; i<=n; i++){
string t=s.substr(0,i);
ll tmp=kmp_count(s,t);
//cout<<t<<endl;
//cout<<tmp<<endl;
if (tmp==1) {
ans+=n-i+1;
break;
}
ans=(ans+tmp)%mod;
}
cout<<ans%mod<<endl;
}
return 0;
}