![POJ 3974 - Palindrome - [字符串hash+二分] POJ 3974 - Palindrome - [字符串hash+二分]](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
题目链接:http://poj.org/problem?id=3974
Time Limit: 15000MS Memory Limit: 65536K
Description
A string is said to be a palindrome if it reads the same both forwards and backwards, for example "madam" is a palindrome while "acm" is not.
The students recognized that this is a classical problem but couldn't come up with a solution better than iterating over all substrings and checking whether they are palindrome or not, obviously this algorithm is not efficient at all, after a while Andy raised his hand and said "Okay, I've a better algorithm" and before he starts to explain his idea he stopped for a moment and then said "Well, I've an even better algorithm!".
If you think you know Andy's final solution then prove it! Given a string of at most 1000000 characters find and print the length of the largest palindrome inside this string.
Input
Output
Sample Input
abcbabcbabcba
abacacbaaaab
END
Sample Output
Case 1: 13
Case 2: 6
题意:
给出若干个字符串,求最长回文子串的长度。
题解:
首先预处理字符串的长度为 $i$ 的前缀子串的哈希值 $pre[i]$,
再把字符串反转,预处理新的字符串的长度为 $i$ 的前缀子串的哈希值 $suf[i]$,
这样,如果在原串中存在一个 $[l_1,r_1]$ 的回文串,那么对应到新串,这个区间就是 $[l_2,r_2] = [len - r_1 +1,len - l_1 + 1]$,这两个子串的哈希值应当是相等的,即:
$pre[r_1 ] - pre[l_1 - 1] \times P^x = suf[r_2 ] - suf[l_2 - 1] \times P^x$
其中,$x = r_1 - l_1 + 1 = r_2 - l_2 +1$。
所以,不难想到,我们如果二分回文子串的长度,就可以 $O\left( {\left| S \right|\log \left| S \right|} \right)$ 求出最长回文子串。
但是,这样做的话,在测样例时就会发现问题,奇数长度的回文子串和偶数长度的回文子串应当是分开计算的(因为回文串两侧同时各去掉一个字符,依然是回文串,且不改变奇偶性),
所以,需要两次二分,一次二分求得长度为偶数的最长回文子串(的长度),再一次二分求得长度为奇数的最长回文子串(的长度)。
最后输出两者中大的即可。
AC代码:
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef unsigned long long ull; const int P=;
const int maxn=+; int len;
char s[maxn];
int q; ull pre[maxn],suf[maxn],Ppow[maxn];
void pretreat()
{
pre[]=;
suf[]=;
Ppow[]=;
for(int i=;i<=len;i++)
{
pre[i]=pre[i-]*P+(s[i]-'a'+);
suf[i]=suf[i-]*P+(s[len-i+]-'a'+);
Ppow[i]=Ppow[i-]*P;
}
} bool found(int x)
{
for(int l1=;l1+x-<=len;l1++)
{
int r1=l1+x-;
int r2=len-l1+,l2=r2-x+;
ull A=pre[r1]-pre[l1-]*(Ppow[x]);
ull B=suf[r2]-suf[l2-]*(Ppow[x]);
if(A==B) return ;
}
return ;
} int main()
{
int kase=;
while(scanf("%s",s+) && s[]!='E')
{
len=strlen(s+);
pretreat(); int l=,r=len/,mid;
while(l<r)
{
mid=(l+r)/+;
if(found(*mid)) l=mid;
else r=mid-;
}
int ans1=l*; l=,r=(len-)/;
while(l<r)
{
mid=(l+r)/+;
if(found(*mid+)) l=mid;
else r=mid-;
}
int ans2=l*+; printf("Case %d: %d\n",++kase,max(ans1,ans2));
}
}