题目:
http://acm.hdu.edu.cn/showproblem.php?pid=3336
题意:
求出字符串的前缀在字符串中重复的总次数。
思路:
kmp 的原始next 数组,next[i]表示前i-1个字符中前后匹配的最大长度是next[i].
将前后匹配的串个数相加 + 字符串的长度 即可得到答案。
AC.
#include <iostream>
#include <cstdio>
using namespace std;
const int mod = 10007;
const int maxn = 2e5+5;
char t[maxn];
int net[maxn];
int n;
void getnext()
{
int i = 0, j = -1;
net[0] = -1;
while(i < n) {
if(j == -1 || t[i] == t[j]) {
++i; ++j;
net[i] = j;
}
else j = net[j];
}
}
int main()
{
//freopen("in", "r", stdin);
int T;
scanf("%d", &T);
while(T--) {
scanf("%d", &n);
scanf("%s", t);
getnext();
int res = net[n] + n;
for(int i = 0; i < n; ++i) {
if(net[i] > 0 && net[i] + 1 != net[i+1]) {
res = (res + net[i]) % mod;
}
}
printf("%d\n", res);
}
return 0;
}