题面
大秦为你打开题目传送门
题目描述
求出一个字符串最短的循环节个数。
思路
不难想到 KMP,KMP 的 next 数组的定义就是长度最长且相等的真前后缀,直接去找 $n-next[n]$ 这个长度就是我们要找的最短循环节长度,用总长除以他即可(别忘了前提是得整除)
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #include<bits/stdc++.h> using namespace std;
const int N = 1e6 + 10;
char s[N]; int n;
int nxt[N];
inline void Input() { scanf("%s", s + 1); if(s[1] == '.') return exit(0); }
inline void InitNxt() { for(int i = 2, j = 0; i <= n; i++) { while (j && s[i] != s[j + 1]) j = nxt[j]; if (s[i] == s[j + 1]) j++; nxt[i] = j; } }
inline void Work() { n = strlen(s + 1); InitNxt();
printf("%d\n", n/(n - nxt[n])); }
int main() { int T = -1; while(T--) { Input(); Work(); } return 0; }
|