Kolya got string $ s $ for his birthday, the string consists of small English letters. He immediately added $ k $ more characters to the right of the string. Then Borya came and said that the new string contained a tandem repeat of length $ l $ as a substring. How large could $ l $ be? See notes for definition of a tandem repeat.写出c++代码
时间: 2023-12-28 09:04:05 浏览: 120
很高兴为您解答问题!以下是C语言代码:
```c
#include <stdio.h>
#include <string.h>
#define MAXN 100005
int n, k, len;
char s[MAXN], t[MAXN * 2];
int fail[MAXN * 2];
int max(int a, int b) { return a > b ? a : b; }
void get_fail() {
fail[0] = fail[1] = 0;
for (int i = 1; i < len; ++i) {
int j = fail[i];
while (j && t[i] != t[j]) j = fail[j];
fail[i + 1] = t[i] == t[j] ? j + 1 : 0;
}
}
int main() {
scanf("%s%d", s, &k);
n = strlen(s), len = n + k;
for (int i = 0; i < len; ++i) t[i] = i < n ? s[i] : s[i - n];
get_fail();
int ans = 0;
for (int i = 1; i < len; ++i) {
int cur = fail[i];
while (cur > n) cur = fail[cur];
if (cur * 2 >= n) ans = max(ans, cur);
}
printf("%d\n", ans);
return 0;
}
```
这个问题是一个字符串算法的经典题目,采用 KMP 算法可以在线性时间内解决。
阅读全文