For each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, inclusive), we want to know whether the prefix is a periodic string. That is, for each i (2 <= i <= N) we want to know the largest K > 1 (if there is one) such that the prefix of S with length i can be written as A
K , that is A concatenated K times, for some string A. Of course, we also want to know the period K.
3 aaa 12 aabaabaabaab 0
Test case #1 2 2 3 3 Test case #2 2 2 6 2 9 3 12 4
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<iostream>
#include<algorithm>
const int maxn=1e6+10;
char s[maxn];
int Next[maxn];
void getNext()
{
int i=0;
int j=-1;
int l=strlen(s);
while(i<l)
{
if(j==-1||s[i]==s[j])
{
i++;
j++;
Next[i]=j;
}
else j=Next[j];
}
}
int main()
{
int n,r=1;
while(~scanf("%d",&n)&&n)
{
scanf("%s",s);
Next[0]=-1;
getNext();
printf("Test case #%d\n",r++);
for(int i=1;i<=n;i++)
{
int ans=i-Next[i];
if(i%ans==0&&i!=ans)
{
printf("%d %d\n",i,i/ans);
}
}
printf("\n");
}
}