留个回文串的版QAQ
这个算法。。和扩展KMP是一样的。。不过一个是顺着一个是回文。。。
int far = 0, ans = 0;
for (int i = 1; s[i]; ++i) {
int already = p[far] + far;
p[i] = already > i ? min(already - i, p[(far << 1) - i]) : 1;
while (s[i - p[i]] == s[i + p[i]]) ++p[i];
if (i + p[i] >= already) far = i; ans = max(ans, p[i] - 1);
}
题目点这里 模板题。。。。
然后它倒腾了我好久 = = 一直WA WA WA。。。。。。。。orz
为了防止要特判回文串长度的奇偶性。。把每个字符中间塞一个莫名其妙的的字符就行T_T
然后就扩展KMP改一改……再改一改……
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int Nmax = 110005;
char st[Nmax], s[Nmax << 1];
int p[Nmax << 1];
int main()
{
while (~scanf("%s", st + 1)) {
int i; for (i = 1; st[i]; ++i) {
s[i << 1] = st[i];
s[(i << 1) + 1] = '&';
}
s[i << 1] = 0; s[0] = '#'; s[1] = '&';
int far = 0, ans = 0;
for (int i = 1; s[i]; ++i) {
int already = p[far] + far;
p[i] = already > i ? min(already - i, p[(far << 1) - i]) : 1;
while (s[i - p[i]] == s[i + p[i]]) ++p[i];
if (i + p[i] >= already) far = i; ans = max(ans, p[i] - 1);
}
printf("%d\n", ans);
}
return 0;
}