题意:给出一个字符串,求它所有前缀在此字符串中出现的次数。
分析:一看,肯定是kmp中 next[i] 求以下标i-1结尾的字符串,使得最长的(前缀==后缀)的长度。很好想到,当next非零时,肯定和前缀有匹配,自然ans+1。当一个前缀出现多次,当next[j]!=0,ans+1,j=next[j],一直往前跳,直到next[j]为0,如果不为0,ans+1。这里比较难理解,next[i]表示的是长度,当跳一次,长度必然减短,如果这个短的长度的前缀在这个长的中出现了,是不是ans仍然要+1。如aabaab,next{0,0,1,0,1,2,3},当next[i]=2时,跳到下标为2的字符,它对应的next[2]=1,也就是说长度为1的前缀在这个大的长度字符串“aabaa”中出现了,所以ans+1。这只是统计前缀在在后面出现的次数,它自身还没算,所以最中ans+n。
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <string.h>
#include <map>
#include <set>
using namespace std;
#define maxn 200000+5
int Next[maxn];
void getNext(string str)
{
int i,j;
int len=str.length();
Next[0]=Next[1]=0;
for(i=1;i<len;i++)
{
j=Next[i];
while(str[i]!=str[j])
{
if(j==0)break;
j=Next[j];
}
if(str[i]==str[j])
Next[i+1]=j+1;
else
Next[i+1]=0;
}
}
int main()
{
int ans,t,n,i,j;
string str;
cin>>t;
while(t--)
{
cin>>n;
cin>>str;
getNext(str);
ans=n%10007;
int len=str.length();
for(i=0;i<=len;i++)
{
j=Next[i];
while(j!=0)
{
ans++;
ans%=10007;
j=Next[j];
}
}
cout<<ans%10007<<endl;
}
return 0;
}