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
stostootsstoSample 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
【题目大意】
求一个字符串的所有的循环节。
【题目分析】
显然,整个字符串的循环节是比较简单的,即l-ne[l],那么我们考虑一下如何求出所有的循环节,这样子求出整个字符串的循环节之后,我们可以想象到,整个字符串分成两个部分,前面和后面(这句是废话)。对于分割点k 可以知道s[1]=s[k+1]…以此类推,那么前半部分的循环节同样也是ne[k],那么我们只需要不断的next,直到不能继续位置,然后用总长减去ne[j]就是循环节的所有情况了。
【代码】
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
char a[1000001];
int ne[1000001],kase=0,out[1000001];
int main()
{
int tt;
scanf("%d",&tt);
while (tt--)
{
scanf("%s",a+1);
int l=strlen(a+1);
for (int i=2,j=0;i<=l;++i)
{
while (j&&a[j+1]!=a[i]) j=ne[j];
if (a[j+1]==a[i]) j++;
ne[i]=j;
}
int ans=0,p=l,top=0;
while (p)
{
ans++;
p=ne[p];
out[++top]=p;
}
printf("Case #%d: %d\n",++kase,ans);
p=l;
for (int i=1;i<=top;++i)
if (i!=top)
printf("%d ",l-out[i]);
else printf("%d",l-out[i]);
printf("\n");
}
}