题意:求字符串中循环节出现的次数
KMP!!!
#include<cstdio> #include<iostream> #include<cstring> #define M 1000010 using namespace std; int fail[M],a[M],m; char ch[M]; void kmp_init() { fail[1]=0; for(int i=2;i<=m;i++) { int p=fail[i-1]; while(p&&a[p+1]!=a[i])p=fail[p]; if(a[p+1]==a[i]) fail[i]=p+1; else fail[i]=0; } } int main() { while(scanf("%s",ch)) { if(ch[0]==‘.‘)break; memset(fail,0,sizeof(fail)); m=strlen(ch); for(int i=1;i<=m;i++) a[i]=ch[i-1]; kmp_init(); int ans=m-fail[m]; if(m%ans==0)printf("%d\n",m/ans); else printf("1\n"); } return 0; }
时间: 2024-10-12 15:20:45