题目链接:https://vjudge.net/contest/238229#problem/G
这个题主要体现KMP算法的多用途,准确的说是next数组的多用途,对于更好的理解next数组有很大帮助。首先,next数组的含义是什么呢?next[i]表示,有前缀为str[0...i-1],对于这个子串,它的前缀与后缀的最长公共长度,如串ABRACADABRD,那么next[10]=3,因为他的前缀与后缀的公共长度为ABR,也就是3。所以,如果一个i字符的字符串为一个周期串,那么前缀与后缀错位的部分就一定是一个循环节,所以K(i-next[i])==i。
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int maxn = 1000000 + 50;
char str[maxn];
int nxt[maxn];//next数组
int main()
{
int n;
int index = 1;
while (scanf("%d", &n)!= EOF)
{
if (n == 0)break;
scanf("%s", str);
memset(nxt, 0, sizeof(nxt));
nxt[0] = 0;
nxt[1] = 0;
for (int i = 1; i < n; i++)
{
int j = nxt[i];
while (j&&str[i] != str[j])
{
j = nxt[j];
}
nxt[i + 1] = (str[i] == str[j] ? j + 1 : 0);
}
printf("Test case #%d\n", index++);
for (int i = 2; i <= n; i++)
{
if (nxt[i] > 0 && i % (i - nxt[i]) == 0)
{
printf("%d %d\n", i, i / (i - nxt[i]));
}
}
printf("\n");
}
return 0;
}