题目链接
http://acm.hdu.edu.cn/showproblem.php?pid=3336
题意
给你一个字符串,求它的每一个前缀出现的次数。
思路
先扩展kmp得到next数组,该字符串的每一个后缀的next值的和就是答案。
因为对于一个后缀,它的next值表示的是它和该字符串的前缀的最大匹配长度,比如说如果next[i]为3,后缀为abcd,这个时候字符串的a,ab,abc前缀都出现了一次,所以ans+=3。
代码
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<cmath>
#include<map>
#include<algorithm>
#include<string>
#include<string.h>
#include<set>
#include<queue>
#include<stack>
#include<functional>
using std::pair;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<PII,int> PPI;
typedef pair<ll,int> PLI;
const double PI=acos(-1);
const int maxn = 2e5+10;
const int maxm = 1e6 + 10;
const int mod = 1e4+7;
const int INF = 0x3f3f3f3f;
using namespace std;
int nex[maxn],ex[maxn];
char t[maxn];
int n;
void getnext()
{
int j=0,po=1,len=n;
nex[0]=len;
while(t[j]==t[j+1]&&j+1<len) j++;
nex[1]=j;
for(int i=2;i<len;i++)
{
if(nex[i-po]+i<nex[po]+po) nex[i]=nex[i-po];
else
{
j=nex[po]+po-i;
if(j<0) j=0;
while(i+j<len&&t[j]==t[j+i]) j++;
nex[i]=j;
po=i;
}
}
}
int main()
{
int tt;
cin>>tt;
while(tt--)
{
scanf("%d%s",&n,t);
getnext();
int res=0;
for(int i=0;i<n;i++) res=(res+nex[i])%mod;
printf("%d\n",res);
}
}