Description
给定字符串,求每个前缀的最短循环节长度
Solution
KMP中nex数组的应用,
如果i%(i-nex[i])==0那么这个前缀有最短循环节
Code
#include <cstdio> #include <algorithm> #include <cstring> using namespace std; int n,p[1000010],cas; char s[1000010]; int main(){ while(~scanf("%d ",&n)&&n){ scanf("%s",s+1); memset(p,0,sizeof(p)); for(int i=2,j=0;i<=n;++i){ while(j>0&&s[i]!=s[j+1]) j=p[j]; if(s[i]==s[j+1]) ++j; p[i]=j; } printf("Test case #%d ",++cas); for(int i=2;i<=n;++i) if(p[i]&&(i%(i-p[i])==0)) printf("%d %d ",i,i/(i-p[i])); puts(""); } return 0; }