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
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
思路:kmp+next数组的应用
分析:
1 题目要求的找到所有满足S[i]=S[i+P] for i in [0..SIZE(S)-p-1]的前缀,并且长度为p。利用上面的式子可以等价的得到等式s[0,len-p-1] = s[p , len-1].
2 给个next数组的性质
假设现在有一个字符串为ababxxxxabab。那么求出的next数组为00012001234,那么前缀和后缀最长的匹配数是4,然后下一个前缀和后缀匹配长度为next[4] = 2 , 然后下一个为next[2] = 0。
所以有一个结论就是,假设当前求出的字符串的前缀和后缀的最长的匹配的长度为len,那么下一个满足的前缀和后缀互相匹配的长度为next[len]...依次
3 观察一下上面的等式,我们发现并不是我们所熟悉的前缀和后缀匹配的等价式。那么我们现在来看这个样列
f z u f z u f z u f 长度为10
next 000 01 2 3 456 7
那么根据next数组就得到前缀和后缀的匹配长度依次为 7 4 1 0 ,那么这时候看看题目的p的可能长度为 3 6 9 10,那么有没有发现规律。
代码:
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
const int MAXN=1000000+100;
char P[MAXN];
int f[MAXN];
int s[MAXN];
int m;
void getFail(char *P,int *f)
{
f[0]=f[1]=0;
for(int i=1;i<m;i++)
{
int j=f[i];
while(j && P[i]!=P[j]) j=f[j];
f[i+1]= (P[i]==P[j])?j+1:0;
}
}
int main()
{
int cas=1;
int t;
cin>>t;
while(t--)
{
scanf("%s",P);
printf("Case #%d: ",cas++);
m=strlen(P);
getFail(P,f);
int len=m;
int cnt=1;
while(f[len]!=0)
{
s[cnt++]=f[len];
len=f[len];
}
cnt--;
cout<<cnt+1<<endl;
for(int i=1;i<=cnt;i++)
{
cout<<m-s[i]<<" ";
}
cout<<m<<endl;
}
return 0;
}