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 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[] 数组性质。在 【算法学习】字符串 KMP算法、next数组性质 这篇文章中,已经将整个过程讲得很清楚了。代码如下:

#include 
using 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:洛谷 P1196 [NOI2002]银河英雄传说【带权并查集】
下一篇:洛谷 P2580 于是他错误的点名开始了【字典树/Map】

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年05月05日 05时08分49秒