#10046. 「一本通 2.2 练习 2」OKR-Periods of Words(内附封面)

该文是一道编程题的解析,涉及字符串处理。题目要求计算给定字符串所有前缀的最大周期长度之和,通过KMP算法找出字符串的最长公共前缀,对每个前缀进行处理。在实现过程中需要注意防止答案超出int范围,并优化查找next[next[i]]的时间复杂度,以避免超时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[POI2006] OKR-Periods of Words

题面翻译

对于一个仅含小写字母的字符串 aaapppaaa 的前缀且 p≠ap\ne ap=a,那么我们称 pppaaa 的 proper 前缀。

规定字符串 QQQ(可以是空串)表示 aaa 的周期,当且仅当 QQQaaa 的 proper 前缀且 aaaQ+QQ+QQ+Q 的前缀。

例如 ababab 的一个周期,因为 ababab 的 proper 前缀,且 ababab+ab 的前缀。

求给定字符串所有前缀的最大周期长度之和。

题目描述

A string is a finite sequence of lower-case (non-capital) letters of the English alphabet. Particularly, it may be an empty sequence, i.e. a sequence of 0 letters. By A=BC we denotes that A is a string obtained by concatenation (joining by writing one immediately after another, i.e. without any space, etc.) of the strings B and C (in this order). A string P is a prefix of the string !, if there is a string B, that A=PB. In other words, prefixes of A are the initial fragments of A. In addition, if P!=A and P is not an empty string, we say, that P is a proper prefix of A.

A string Q is a period of Q, if Q is a proper prefix of A and A is a prefix (not necessarily a proper one) of the string QQ. For example, the strings abab and ababab are both periods of the string abababa. The maximum period of a string A is the longest of its periods or the empty string, if A doesn’t have any period. For example, the maximum period of ababab is abab. The maximum period of abc is the empty string.

Task Write a programme that:

reads from the standard input the string’s length and the string itself,calculates the sum of lengths of maximum periods of all its prefixes,writes the result to the standard output.

输入格式

In the first line of the standard input there is one integer kkk (1≤k≤1 000 0001\le k\le 1\ 000\ 0001k1 000 000) - the length of the string. In the following line a sequence of exactly kkk lower-case letters of the English alphabet is written - the string.

输出格式

In the first and only line of the standard output your programme should write an integer - the sum of lengths of maximum periods of all prefixes of the string given in the input.

样例 #1

样例输入 #1

8
babababa

样例输出 #1

24

数据范围与提示

对于全部数据,1<k<1061\lt k\lt 10^61<k<106

人话翻译:

给定一个字符串A,求他所有前缀B(包括A=B)的最大周期,周期即B的前缀C最长,C要满足B是CC的字串。实例:
ABABABAB的所有前缀有:−−−−−−−−−周期为−−−长度ABABABAB的所有前缀有:---------周期为---长度ABABABAB的所有前缀有:周期为长度
A−−−−−−−−−−−−−−−−−−−−无−−−−−0A--------------------无-----0A

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值