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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
关注你微信了!
[***.104.42.241]2024年04月02日 08时28分02秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
002_shell变量 赋值
2019-04-27
003_bash对于脚本换行符格式的要求
2019-04-27
004_变量的声明以及获取
2019-04-27
005_变量的引用与赋值
2019-04-27
006_关于变量定义的状态
2019-04-27
007_shell中把变量重置为null
2019-04-27
008_shell创建只读量
2019-04-27
009_shell中从标准输入信息
2019-04-27
010_bash脚本的参数传递
2019-04-27
011_命令行参数的左移
2019-04-27
012_bash中的if判断条件
2019-04-27
013_bash中的加法
2019-04-27
021_Excel的条件格式
2019-04-27
022_Excel空白值批量填充默认值
2019-04-27
023_emacs git-gutter+报错解决
2019-04-27
024_spacemacs支持org-pomodoro的声音提示
2019-04-27
025_everything搜索使用体验
2019-04-27
026_好用的windows小工具clover
2019-04-27
027-Mac触摸板实现窗口移动
2019-04-27
028_AUTOSAR RTE学习笔记-1
2019-04-27