Description
给定一字符串,求它所有的前缀出现的次数的和
Input
第一行为用例组数T,对于每组用例第一行为字符串长度n,第二行为一个字符串
Output
对于每组用例,输出该字符串所有的前缀出现的次数的和
Sample Input
1
4
abab
Sample Output
6
Solution
直接暴力枚举所有前缀显然会超时,那么只有从动态规划的角度来考虑,首先我们知道next数组中next[i]表示的是以第i个字符结尾的前缀中最长公共前后缀的长度,我们令dp[i]表示以第i个字符结尾的前缀中所含有以第i个字符结尾的前缀的个数,那么显然有dp[i]=dp[next[i]]+1,求出dp数组后累加即为答案
Code
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
#define maxn 222222
#define mod 10007
char s[maxn];
int nex[maxn];
int dp[maxn];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
scanf("%s",s);
for(int i=0,j=-1;i<=n;i++,j++)//求next数组
{
nex[i]=j;
while(~j&&s[i]!=s[j])
j=nex[j];
}
dp[0]=0;
int ans=0;
for(int i=1;i<=n;i++)
{
dp[i]=(dp[nex[i]]+1)%mod;
ans+=dp[i];//累加各前缀出现的次数
ans%=mod;
}
printf("%d\n",ans);
}
return 0;
}