HDU-3336:Count the string

Description

It is well known that AekdyCoin is good at string problems as well as number theory problems. When given a string s, we can write down all the non-empty prefixes of this string. For example:
s: "abab"
The prefixes are: "a", "ab", "aba", "abab"
For each prefix, we can count the times it matches in s. So we can see that prefix "a" matches twice, "ab" matches twice too, "aba" matches once, and "abab" matches once. Now you are asked to calculate the sum of the match times for all the prefixes. For "abab", it is 2 + 2 + 1 + 1 = 6.
The answer may be very large, so output the answer mod 10007.

kmp nxt[]数组。f[i]表示以i-1号字符结尾的可行方案个数。(话说理解了好长时间233)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char p[201000];
int t,nxt[201000],f[201000],len,mod=10007,sum;
void work_nxt()
{
	int k=-1,j=0;nxt[0]=-1;
	while(j<len)
	{
		if(k==-1||p[j]==p[k])
		{
			j++,k++;
			nxt[j]=k;
		}
		else k=nxt[k];
	}
}
int main()
{
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%s",&len,p);
		work_nxt();
		memset(f,0,sizeof(f));sum=0;
		for(int i=1;i<=len;i++)
			f[i]=f[nxt[i]]+1,sum=(sum+f[i])%mod;
		printf("%d\n",sum);
	}
	return 0;
}

 

 

发表评论

邮箱地址不会被公开。 必填项已用*标注