博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HDU 3336 Count the string【KMP的next数组性质】
阅读量:2007 次
发布时间:2019-04-28

本文共 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;}

提交后:

在这里插入图片描述

转载地址:http://kaotf.baihongyu.com/

你可能感兴趣的文章
python urllib
查看>>
APUE初学 环境搭建
查看>>
Binary Tree Level Order Traversal
查看>>
题目1511:从尾到头打印链表
查看>>
SYSTEM V IPC 基本概念
查看>>
Elasticsearch 备份数据到 AWS S3
查看>>
使用rancher配置kong和konga
查看>>
变量字符串${var%%.*}
查看>>
Kong docker部署及简单使用
查看>>
jstat命令查看jvm的GC情况
查看>>
zabbix自动清理30天前的数据
查看>>
nginx针对url参数重写URI
查看>>
python处理日志
查看>>
ELK部署搭建
查看>>
kafka安装与配置
查看>>
filebeat安装配置
查看>>
验证日志信息收集成功
查看>>
彻底删除Kafka中的topic
查看>>
mlanuch文档翻译
查看>>
mloginfo文档翻译
查看>>