分析:
KMP算法入门题,只用到NEXT[]数组,主要在于NEXT[]数组的构建,详细介绍见我前几篇博客,KMP初学
if (next[i] >0 && i%(i-next[i]) == 0)
printf("%d %d\n",i,i/(i-next[i]));
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int maxn=1000005; int next[maxn]; void getNext(int m,string str) { int j=-1; next[0]=j; int i=0; while (i<m) { while (j != -1 && str[i] != str[j]) j=next[j]; i++;j++; if (j>=m) next[i]=next[j-1]; else next[i]=j; } } //-1 0 1 0 1 2 3 4 5 6 7 8 9 int main() { /*string str="aabaabaabaab"; int len=str.size();*/ int len; string str; int kase=0; while (~scanf("%d",&len) && len) { cin>>str; memset(next,0,sizeof(next)); printf("Test case #%d\n", ++kase); getNext(len,str); for (int i=2;i<=len;i++) { if (next[i] >0 && i%(i-next[i]) == 0) printf("%d %d\n",i,i/(i-next[i]));//精髓所在 } } /*for (int i=0;i<=len;i++) printf("%d ",next[i]);*/ return 0;