题目链接:http://acm.fzu.edu.cn/problem.php?pid=1901
题目要求的找到所有满足S[i]=S[i+P] for i in [0..SIZE(S)-p-1]的前缀,并且长度为p。利用上面的式子可以等价的得到等式s[0,len-p-1] = s[p , len-1].
思路:利用next数组的性质,从next[n]往前推即可。
代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int N = 1000005;
char s[N];
int next[N], n, t, ans[N];
void get_next(char *seq, int m) {
next[0] = -1;
int j = next[0];
for (int i = 1; i < m; i++) {
while (j >= 0 && seq[i] != seq[j + 1]) j = next[j];
if (seq[i] == seq[j + 1]) j++;
next[i] = j;
}
}
int main() {
int cas = 0;
scanf("%d", &t);
while (t--) {
int ansn = 0;
scanf("%s", s);
printf("Case #%d: ", ++cas);
n = strlen(s);
get_next(s, n);
int tmp = next[n - 1];
while (tmp != -1) {
ans[ansn++] = n - tmp - 1;
tmp = next[tmp];
}
ans[ansn++] = n;
printf("%d\n", ansn);
printf("%d", ans[0]);
for (int i = 1; i < ansn; i++)
printf(" %d", ans[i]);
printf("\n");
}
return 0;
}