UVA10298 Power Strings 题解
题目链接。
分析
十分优秀的证明,把该证明过程重新整理了一下。
在求解 \(next\) 数组时,相当于我们把字符串这样对齐了一下:

如下图,由于上下两个串是一样的,所以上面有黄色的部分,下面那个串也有;由于中间的部分是相同的,所以黄色的部分和蓝色的部分相同,上面也有,以此类推。

如果 \(n-next_n \nmid n\),相当于第一个字符串放不下最后一个循环节了,此时的串就是不循环的,答案为 \(1\)。
否则串必然是循环的,并且容易证明,此时的答案 \(\frac{n}{n-next_n}\) 是最多的。
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
int nxt[N], n;
char s[N];
int main () {
ios :: sync_with_stdio (0);
cin.tie (0), cout.tie (0);
while (cin >> (s + 1)) {
if (s[1] == '.') return 0;
n = strlen (s + 1);
for (int i = 2, j = 0; i <= n; i++) {
while (j && s[j + 1] != s[i])
j = nxt[j];
if (s[j + 1] == s[i]) j++;
nxt[i] = j;
}
if (!nxt[n] || n % (n - nxt[n])) cout << 1;
else cout << n / (n - nxt[n]);
cout << "\n";
}
}

浙公网安备 33010602011771号