HDU 3336 Count the string【KMP的next数组性质】
发布日期:2021-07-01 02:50:43
浏览次数:4
分类:技术文章
本文共 2053 字,大约阅读时间需要 6 分钟。
题目链接:
Problem Description
It is well known that AekdyCoin is good at string problems as well as number theory problems. When given a strings
, 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 integerT
, 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 ofs
mod 10007
. Sample Input
14abab
Sample Output
6
题意:求出字符串中每个非空前缀在串中的出现次数的总和。
思路:利用KMP算法的 next[]
数组性质。在 【算法学习】字符串 KMP算法、next数组性质
这篇文章中,已经将整个过程讲得很清楚了。代码如下:
#includeusing namespace std;const int maxn = 200010;char s[maxn];int nextArr[maxn], len;/*void getNext() { nextArr[0] = nextArr[1] = 0; int pos = 2, cn = 0; while (pos <= len) { if (s[pos - 1] == s[cn]) nextArr[pos++] = ++cn; else if (cn > 0) cn = nextArr[cn]; else nextArr[pos++] = cn; }}*/void getNext() { nextArr[0] = 0, nextArr[1] = 0; for (int i = 1; i < len; ++i) { int j = nextArr[i]; while (j && s[i] != s[j]) j = nextArr[j]; nextArr[i + 1] = (s[i] == s[j] ? j + 1 : 0); }}int main() { int t; scanf("%d", &t); while (t--) { scanf("%d%s", &len, s); long long prefixNum = len; //最开始可以确定的非空前缀个数(串长度) getNext(); prefixNum += nextArr[len]; //先包含:最后的nextArr值 for (int i = 0; i < len; ++i) if (nextArr[i] > 0 && nextArr[i] + 1 != nextArr[i + 1]) prefixNum += nextArr[i]; //当不满足递推规律时+next值 printf("%lld\n", prefixNum % 10007); } return 0;}
提交后:
转载地址:https://memcpy0.blog.csdn.net/article/details/108313773 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
不错!
[***.144.177.141]2024年05月06日 13时47分37秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
使用libpcap过滤arp
2019-05-01
在VC环境中调试跟踪变量
2019-05-01
[转帖]Robots.txt指南
2019-05-01
Eclipse + MyEclipse下配置J2EE工程(英文界面)
2019-05-01
Eclipse及其插件下载网址大全
2019-05-01
正则表达式简介(微软)--6.优先权顺序
2019-05-01
多用户与多租户的区别
2019-05-01
Python自动化运维 - day14 - JavaScript基础
2019-05-02
oracle保存小数点前为"0"的问题
2019-05-02
linux sar 命令详解
2019-05-02
ipvsadm 安装配置
2019-05-02
Linux shell脚本的字符串截取
2019-05-02
数据库复习(4)
2019-05-02
1小时点击量破千万!阿里巴巴首发:MySQL高级调优笔记!全是技术重点
2019-05-02
这个GItHub上的Java项目开源了 2021最全的Java架构面试复习指南
2019-05-02
Proftpd MySQL [Step by Step]
2019-05-02
EFI Shell 命令参考
2019-05-02