Question link:
Poj: http://poj.org/problem? Id = 1961
HDU: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1358
Zoj: http://acm.zju.edu.cn/onlinejudge/showProblem.do? Problemcode = 2177.
Question:
Returns the shortest cycle section of each prefix of a string s whose length is N. In other words, for each I (2 <= I <= N), evaluate a maximum integer k> 1 (if K exists ), so that the prefix consisting of the first I characters of S is obtained by repeating a string K times. Output all the I with K and corresponding K.
For example, for the aabaabaabaab string, K exists only when I is 2, 6, 9, 12, and is 2, 2, 3, 4
Analysis and Summary:
A classic topic, which is included in various OJ categories.
At the beginning of this question, I just understood KMP, did not see the relevant information of the shortest cycle section, and made a mess. I spent two discrete mathematics classes and thought about it. The result was finally AC =, but unfortunately, the result shows that the HDU and zoj are used again, while the poj is still wa...
Then, you can learn the methods mentioned in "getting started with algorithms-Training Guide" to successfully access the AC on the poj.
Although I have not succeeded in AC on poj, after thinking about this question, I have a deeper understanding and understanding of the process and principle of getting next through the KMP mismatch function.
Code:
1. Self-built code. poj cannot communicate with each other.
#include<cstdio>#include<cstring>const int MAXN = 1000005;char T[MAXN];int f[MAXN];int n;void getFail(char *P, int *f){ f[0]=f[1]=0; int start=1; int n=strlen(P); bool flag=true; for(int i=1; i<n; ++i){ int j=f[i]; while(j && P[i]!=P[j]){ flag=false; j=f[j]; } if(P[i]==P[j]){ f[i+1]=j+1; if(f[i+1]==1){ flag=true; start=i; } if(flag && (i+1)>=start*2 && (i+1)%start==0){ printf("%d %d\n",i+1,(i+1)/start); } } else{ flag=true; start=i+1; f[i+1]=0; } }}int main(){ int cas=1; char ch; while(~scanf("%d%*c",&n) && n){ printf("Test case #%d\n",cas++); gets(T); getFail(T,f); puts(""); } return 0;}
2. I learned from Liu lujia's big white book (algorithm entry classic-Training Guide.
#include<cstdio>#include<cstring>const int MAXN = 1000005;char T[MAXN];int f[MAXN];int n;void getFail(char *P, int *f){ f[0]=f[1]=0; int start=1; int n=strlen(P); for(int i=1; i<n; ++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; char ch; while(~scanf("%d%*c",&n) && n){ printf("Test case #%d\n",cas++); gets(T); getFail(T,f); for(int i=2; i<=n; ++i){ if(f[i]>0 && i%(i-f[i])==0){ printf("%d %d\n",i,i/(i-f[i])); } } puts(""); } return 0;}
-- The significance of life is to give it a meaningful person.
Original Http://blog.csdn.net/shuangde800,
D_double (reprinted please mark)