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<string.h>
using namespace std;
const int N = 1000005;
char p[N];
int next[N];
void getNext(char p[],int n,int next[]){
int j=0;
int t=-1;
next[0]=-1;
while(j<n){
if(t<0||p[j]==p[t]){
next[++j]=++t;
}
else t=next[t];
}
}
int main(){
int n;
int cas=0;
while(scanf("%d",&n)!=EOF&&n){
scanf("%s",p);
getNext(p,n,next);
printf("Test case #%d\n",++cas);
for(int i=0;i<n;i++){
int m=i+1;
int k=m-next[m];
if(m!=k&&m%k==0) printf("%d %d\n",m,m/k);
}
printf("\n");
}
return 0;
}