字符串hash+二分答案
字符串hash+二分答案
Palindrome poj 3974
求一个字符串的最长回文子串。
因为在学字符串hash,所以这里用二分答案和字符串hash来做,复杂度是O(N log N),据说manacher算法可以在O(N)解决这个问题,但是我还没学哈哈哈哈以后补吧
题解:枚举回文子串的中心位置,i = 1 ~ n,二分从该位置往两边扩展的最长相同字符的数目,然后记录答案。(分偶数和奇数的回文子串二分)
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
unsigned long long f1[1000010], f2[1000010], p[1000010];
int main() {
for(int t = 1; ; t++) {
char s[1000010];
int ans = 0;
scanf("%s", s+1);
int n = strlen(s+1);
if(n == 3 && s[1] == 'E' && s[2] == 'N' && s[3] == 'D') {
break;
}
f1[0] = f2[n+1] = 0;
p[0] = 1;
for(int i = 1; i <= n; i++) {
f1[i] = f1[i-1] * 131 + (s[i] - 'a' + 1);
f2[n-i+1] = f2[n-i+2] * 131 + (s[n-i+1] - 'a' + 1);
p[i] = p[i-1] * 131;
}
int l, r;
for(int i = 1; i < n; i++) {//回文子串是奇数
l = 0, r = min(i - 1, n - i);
while(l < r) {
int mid = (l + r + 1) / 2;
if(f1[i-1] - f1[i-mid-1] * p[mid] == f2[i+1] - f2[i+mid+1] * p[mid]) l = mid;
else r = mid - 1;
}
if(l * 2 + 1 > ans) ans = l * 2 + 1;
}
for(int i = 1; i < n; i++) {//回文子串是偶数
l = -1;
if(s[i] == s[i+1]) {
l = 0, r = min(i - 1, n - i - 1);
while(l < r) {
int mid = (l + r + 1) / 2;
if(f1[i-1] - f1[i - mid - 1] * p[mid] == f2[i+2] - f2[i+mid+2] * p[mid]) l = mid;
else r = mid - 1;
}
}
if((l + 1) * 2 > ans) ans = (l + 1) * 2;
}
printf("Case %d: %d\n", t, ans);
}
return 0;
}