题目:
链接:http://acm.hdu.edu.cn/showproblem.php?pid=3336
算法:
字符串KMP。好的,先来复习一下在KMP中next数组是怎么求的?next[i]表示在i位置前面的串的前缀和后缀相等的长度。例如:abab:-1 0 0 1;其中b位置处next为1,表示串aba中的前缀a和后缀a相等,长度为1。
首先,我们规定第一个字符的模式值为-1,若S[j] == S[k],那么就有next[j+1] = next[k+1];若不相等,即前后缀匹配失败,k = next[k]。
思路:
利用next数组求出每个prefix的匹配串个数。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int t,n;
char s[200020],s1[200020];
int next[200020];
void get_nextval()
{
int i,j;
i=-1;
j=0;
next[0]=-1;
while (j<n)
{
if(i==-1 || s[i]==s[j])
{
j++; i++;
next[j]=i;
}
else
i=next[i];
}
}
int main()
{
//freopen("input.txt","r",stdin);
int sum,j;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
getchar();
gets(s);
get_nextval();
sum = n; //一定存在的串个数
for(int i=1; i<=n; i++)
{
for(j=next[i]; j; sum++)
j = next[j];
sum %= 10007;
}
printf("%d\n",sum);
}
return 0;
}