HDU - 3336 Count the string dp+kmp

题目链接:点击查看

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. 

Input

The first line is a single integer T, indicating the number of test cases. 
For each case, the first line is an integer n (1 <= n <= 200000), which is the length of string s. A line follows giving the string s. The characters in the strings are all lower-case letters. 

Output

For each case, output only one number: the sum of the match times for all the prefixes of s mod 10007.

Sample Input

1
4
abab

Sample Output

6

题意:所有前缀一共出现了多少次

题解:dp[i] 表示以i-1为结尾的含有前缀的数量   那么  dp[i] = dp[ nex[i] ]  + 1

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=400100;
const int mod=10007;
char s[N];
int nex[N],dp[N],len;
void getnex()
{
	int i=0,j=-1;
	nex[0]=-1;
	while(i<len)
	{
		if(j==-1||s[i]==s[j]) nex[++i]=++j;
		else j=nex[j];
	}
}
int main()
{
	int T;
	scanf("%d",&T); 
	while(T--)
	{
		scanf("%d%s",&len,s);
		getnex();
		int ans=0;dp[0]=0;
		for(int i=1;i<=len;i++)
		{
			dp[i]=dp[nex[i]]+1;
			ans=(ans+dp[i])%mod;
		}
		printf("%d\n",ans);
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/mmk27_word/article/details/86716567