J - Count the string
后缀ans+1,接着对next回溯一直到为0,相当于把子串里蕴含的前缀子串也找出来,举个例子:
s a b a b a
i 0 1 2 3 4 5
next[i] -1 0 0 1 2 3
开始 ans=5
next[3] = 1,ans + 1 = 6,next[1] = 0
next[4] = 2,ans + 1 = 7,next[2] = 0
next[5] = 3,ans + 1 = 8,next[3] = 1,ans + 1 = 9(这里就表示在aba这个后缀里还蕴涵着一个前缀a)
所以最后答案是9
#include<bits/stdc++.h>
using namespace std;
#define maxn 300000
int n,nxt[maxn],ans,temp;
string str;
void getnext()
{
int i=0,j=-1;
nxt[0]=-1;
while(i<n)
{
if(j==-1||str[i]==str[j])
{
i++;
j++;
nxt[i]=j;
}
else
j=nxt[j];
}
}
int main()
{
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--)
{
memset(nxt,0,sizeof(nxt));
cin>>n>>str;
ans=n;
getnext();
for(int i=1; i<=str.size(); i++)
{
temp=nxt[i];
while(temp)
{
ans=(ans+1)%10007;
temp=nxt[temp];
}
}
cout<<ans<<endl;
}
return 0;
}