HDU 3336 Count the string【KMP的next数组性质】
发布日期:2021-07-01 02:50:43
浏览次数:3
分类:技术文章
本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
留言是一种美德,欢迎回访!
[***.207.175.100]2024年05月05日 05时08分49秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
GDB命令大全
2019-05-02
gdb调试正在运行的进程
2019-05-02
GDB调试子进程
2019-05-02
使用truss、strace或ltrace诊断软件的"疑难杂症"
2019-05-02
联合体union
2019-05-02
Linux命令ldconfig——动态链接库管理命令
2019-05-02
GNU GDB Debugger
2019-05-02
exec函数族
2019-05-02
指针以及内存分配
2019-05-02
做为一个社会的人,不是靠能写多少行代码,代码多么优雅水平多么高来衡量身家的。
2019-05-02
DOS/Windows和Linux/Unix间文件格式和字符集转换
2019-05-02
ioctl 的使用方法详细说明与例子
2019-05-02
ioctl 官方说明
2019-05-02
S_ISDIR S_ISREG等常见的几个宏
2019-05-02
IT行业培训必读:优秀程序员的十个习惯
2019-05-02
通过 ulimit 改善系统性能
2019-05-02
Linux中的tty,pty与pts以及/dev下各种tty设备
2019-05-02
gdbserver远程调试
2019-05-02
openlog、syslog和closelog函数
2019-05-02