一、题目描述
二、算法分析说明与代码编写指导
注意:本代码中所有字符串的下标都是从 1 开始的。
next 数组的意义:
next[j]的值 = 模式串在位置j以前的 (j – 1) 个字符的前后缀相等的长度 + 1。
(当字符串的下标从 0 开始时,next[j]的值 = 模式串在位置j以前的 j 个字符的前后缀相等的长度)
令 i = n + 1,n,n - 1,……。i 要从这 n + 1 个位置开始不断根据 next 数组往前跳,每跳一次代表数到某一个前缀出现一次。当跳出字符串开头时,从下一个位置开始尝试起跳。
这样做是因为由于 next 数组只刻画了最长相同真前后缀的长度,而同一个前缀在整个字符串中可能出现多次。夹在字符串开头与结尾中间的那几次出现也需要被统计进来,所以每个位置都要进行搜寻。
画示意图可以发现,当一个前缀在字符串中总共出现 k 次时,每一个 i 值只能统计一次该前缀的出现次数。当一个较长的相同前后缀中还有相同的真前后缀时,通过内层循环 j = next[j] 的跳跃方式可以将这些相同的前后缀一并统计。
三、AC 代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#pragma warning(disable:4996)
template<class _Nty> inline void getnext(const char* const _Pattern, _Nty* const _Next, const _Nty& _PatternLen) {
_Nty i = 1, j = 0; _Next[1] = 0;
while (i <= _PatternLen) {
if (j == 0 || _Pattern[i] == _Pattern[j]) { ++i, ++j, _Next[i] = j; }
else j = _Next[j];
}
}//The index of the head of _Pattern string is 1.
const unsigned lmax = 200003, m = 10007;
unsigned t, n, next[lmax], a, cnt[lmax]; char s[lmax];
int main() {
scanf("%u", &t); ++t;
while (--t) {
scanf("%u", &n); getchar(); fgets(s + 1, lmax, stdin);
getnext(s, next, n); a = 0;
for (unsigned i = n + 1; i; --i) {
for (unsigned j = i; next[j]; j = next[j]) { ++a; }
a %= m;
}
printf("%u\n", a);
}
return 0;
}