题目: http://acm.hdu.edu.cn/showproblem.php?pid=3336
题意:
给定一个串s;
求各个前缀的出现次数之和。
分析:
用KMP求得next数组之后,将next数组中递增的一串数的最后一个加到答案中即可;
别忘了每个前缀自己也算出现了一次。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long llong;
const int tmax=200005;
const llong mod=10007;
int len,f[tmax];
char s[tmax];
void work()
{
llong ans=len;
for(int i=2;i<=len;i++)
{
if(f[i+1]==f[i]+1) continue;
ans=(ans+f[i])%mod;
}
cout<<ans<<endl;
return;
}
void getfail()
{
int i=0,j=-1;
f[0]=-1;
while(i<len)
{
if(j==-1||s[i]==s[j])
{
i++;
j++;
f[i]=j;
}
else j=f[j];
}
return;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&len);
scanf("%s",s);
getfail();
f[len+1]=0;
work();
}
return 0;
}