hdu3336 Count the string--KMP+DP
发布日期:2021-10-03 20:31:48 浏览次数:2 分类:技术文章

本文共 1854 字,大约阅读时间需要 6 分钟。

原题链接:

一:原题内容

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

二:分析理解

题意:求给定字符串含前缀的数量

abab

前缀为

a

ab

aba

abab

abab中共有六个子串是前缀a a ab ab aba abab

所以答案为6

dp[ i ]表示形如上图两红线的前缀个数。

三:AC代码

#define _CRT_SECURE_NO_DEPRECATE     #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1  #include
#include
using namespace std;char p[200010];int nextval[200010];int dp[200010];int p_len;void GetNextval(){ int i = 0, j = -1; nextval[0] = -1; while (i < p_len) { if (j == -1 || p[i] == p[j]) { i++; j++; nextval[i] = j; } else j = nextval[j]; }}int DP(){ GetNextval(); dp[0] = 0; int ans = 0; for (int i = 1; i <= p_len; i++) { dp[i] = dp[nextval[i]] + 1; cout << dp[i] << " "; ans += dp[i]; ans %= 10007; } cout << endl; return ans;}int main(){ int N; scanf("%d", &N); while (N--) { scanf("%d", &p_len); scanf("%s", p); printf("%d\n", DP()); } return 0;}

转载地址:https://blog.csdn.net/LaoJiu_/article/details/50931372 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:hdu3068 最长回文--Manacher算法
下一篇:hdu2087 剪花布条--KMP

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月02日 08时28分02秒