HDU3336Count the string(KMP+动态规划)

来源:互联网 发布:mysql返回上一级 编辑:程序博客网 时间:2024/05/22 00:11
Problem 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.
 

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
14abab
 

Sample Output
6


思路:这道题主要运用KMP的next数组,完全理解next数组这道题就好做了

#include<iostream>#include <cstdio>#include <cstring>using namespace std;const int MAXN = 200000+5;int Next[MAXN],dp[MAXN];int n,T;char p[MAXN];void getNext(){int i,j;Next[0] = 0;Next[1] = 0;for(i = 1;i<n;i++){j = Next[i];while(j&&p[i]!=p[j])j = Next[j];Next[i+1] = p[j] == p[i]?j+1:0;}}int main(){int T;scanf("%d",&T);while(T--){memset(dp,0,sizeof(dp));int i,sum = 0;scanf("%d",&n);scanf("%s",p);getNext();for(i = 0;i<n;i++){dp[i+1] = dp[Next[i+1]]+1;sum+=dp[i+1];sum = sum%10007;}printf("%d\n",sum);}return 0;}


0 0