题面
解法
KMP算法的经典应用
- 因为最终的循环节不一定是长度的约数,如果一定是,那么我们可以枚举然后字符串哈希,这个复杂度是 O(n) O ( n ) 的
- 考虑一下KMP算法中 nxt n x t 数组的定义,即为最长的前缀=后缀的长度(不包括自己)。可以发现,如果存在循环节 A A ,那么类似于形式的后缀一定能由一个长度和它相同的前缀来表示
- 所以,显然答案即为 n−nxt[n] n − n x t [ n ]
- 时间复杂度: O(n) O ( n )
代码
#include <bits/stdc++.h>
#define N 1000010
using namespace std;
template <typename node> void read(node &x) {
x = 0; int f = 1; char c = getchar();
while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
char st[N];
int nxt[N];
int main() {
int n; read(n);
scanf(" %s", st + 1);
for (int i = 2; i <= n; i++) {
int j = nxt[i - 1];
while (j && st[j + 1] != st[i]) j = nxt[j];
if (st[j + 1] == st[i]) j++;
nxt[i] = j;
}
cout << n - nxt[n] << "\n";
return 0;
}