Problem Description
For each prefix with length P of a given string S,if
S[i]=S[i+P] for i in [0..SIZE(S)-p-1],
then the prefix is a “period” of S. We want to all the periodic prefixs.
Input
Input contains multiple cases.
The first line contains an integer T representing the number of cases. Then following T cases.
Each test case contains a string S (1 <= SIZE(S) <= 1000000),represents the title.S consists of lowercase ,uppercase letter.
Output
For each test case, first output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the number of periodic prefixs.Then output the lengths of the periodic prefixs in ascending order.
Sample Input
4
ooo
acmacmacmacmacma
fzufzufzuf
stostootssto
ooo
acmacmacmacmacma
fzufzufzuf
stostootssto
Sample Output
Case #1: 3
1 2 3
Case #2: 6
3 6 9 12 15 16
Case #3: 4
3 6 9 10
Case #4: 2
9 12
1 2 3
Case #2: 6
3 6 9 12 15 16
Case #3: 4
3 6 9 10
Case #4: 2
9 12
题意:给你一个字符串str,对于每个str长度为p的前缀,如果str[i]==str[p+i](p+i<len),那么我们认为它是一个periodic prefixs.求所有满足题意的前缀的长度p。
知识点:KMP算法、对next数组的理解
KMP算法中next数组的含义是什么?
next数组:失配指针
如果目标串的当前字符i在匹配到模式串的第j个字符时失配,那么我们可以让i试着去匹配next(j)
对于模式串str,next数组的意义就是:
如果next(j)=t,那么str[1…t]=str[len-t+1…len]
我们考虑next(len),令t=next(len);
next(len)有什么含义?
str[1…t]=str[len-t+1…len]
那么,长度为len-next(len)的前缀显然是符合题意的。
接下来我们应该去考虑谁?
t=next( next(len) );
t=next( next (next(len) ) );
一直下去直到t=0,每个符合题意的前缀长是len-t
#include <cstdio>
#include <cstring>
const int maxn = 1000010;
int p[maxn],ans[maxn];
char str[maxn];
void get_p(int len){
p[1] = 0;
int j = 0;
for(int i = 2;i <= len;i++){
while(j > 0 && str[j+1] != str[i]) j = p[j];
if(str[j+1] == str[i]) j++;
p[i] = j;
}
}
int main(){
int nkase;
scanf("%d",&nkase);
for(int kase = 1;kase <= nkase;kase++){
scanf("%s",str+1);
int len = strlen(str+1);
get_p(len);
int t = p[len],cnt = 0;
while(t){
ans[cnt++] = len-t;
t = p[t];
}
ans[cnt++] = len;
printf("Case #%d: %d\n",kase,cnt);
for(int i = 0;i < cnt-1;i++) printf("%d ",ans[i]);
printf("%d\n",ans[cnt-1]);
}
return 0;
}