链接:http://acm.hdu.edu.cn/showproblem.php?pid=3336
题意:给一串字符串,问这串字符串所有的前缀总共在这个字符串中出现了几次。
举个例子:字符串abab。a出现了2次,ab出现了2次,aba1次,abab1次,总共6次。
准备工作 : 解这道题就要对kmp算法中的next[] 数组有着深刻的理解,如字符串str的next[i] = j。就代表 str中j-i+1这个字符串和0-j这个字符串相等
解题思路 : 将字符串所有的前缀0-i在i+1-n出现的次数相加得到 sum, sum再加上n就是了(共有n个字符串)。
#include <stdio.h>
#include <string.h>
#define N 200000+100
void nextMake(const char *p,int *next);
void kmp(const char *T,const char *p,int *next);
char str1[N],str2[N];
int sum,next[N],dp[N];
int main()
{
int t,n,i,j;
scanf("%d",&t);
while(t--)
{
sum = 0;
scanf("%d %s",&n,str1);
nextMake(str1,next);
n = strlen(str1);
for(i=0; i<n; i++)
{
/*比如str=abab这个字符串,next[3] = 2,不就是就表示与
缀在str[i-n-1]找到了一个匹配吗,所以sum += 1*/
if(next[i] != 0)
sum = (sum+1)%10007;
}
printf("%d\n",(sum+n)%10007);
}
return 0;
}
void nextMake(const char *p,int *next)
{
int k,q;
int m = strlen(p);
next[0] = 0;
for(q=1,k=0; q<m; q++)
{
while(k>0 && p[q]!=p[k])
k = next[k-1];
if(p[k] == p[q])
{
k++;
}
next[q] = k;
}
}