Description
Andy the smart computer science student was attending an algorithms class when the professor asked the students a simple question, "Can you propose an efficient algorithm to find the length of the largest palindrome in a string?"
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
Your program will be tested on at most 30 test cases, each test case is given as a string of at most 1000000 lowercase characters on a line by itself. The input is terminated by a line that starts with the string "END" (quotes for clarity).
Output
For each test case in the input print the test case number and the length of the largest palindrome.
Sample Input
abcbabcbabcba abacacbaaaab END
Sample Output
Case 1: 13 Case 2: 6
题意: 题目给出多组字符串,对于每组字符串输出其最长回文子串。
分析: 判断字符串回文显然需要用到字符串哈希,之后可以考虑对于每个点二分,二分以该点为中心能向两侧延伸多长的回文串。例如,有字符串babe,对于第二个字符'a',由于最小可能延伸距离为0,二分左端点也就为0,最长可能延伸距离为1,二分右端点也为1,经过二分查找后得到最终可延伸距离为1,最后得到以第二个字符'a'为中心的回文串长度为2*可延伸长度+1,即为3。上面的分析针对于奇数长度回文串,偶数长度回文串也类似,找到中心以后二分即可。
具体代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define P 131
using namespace std;
char s[1000005];
unsigned long long p[1000005], h1[1000005], h2[1000005];
signed main()
{
int times = 0;
while(1)
{
scanf("%s", s+1);
if(strcmp(s+1, "END") == 0)
break;
times++;
int len = strlen(s+1);
p[0] = 1;
h2[len+1] = 0;//这里加不加都可以,因为使用的时候被减掉了
for(int i = 1; i <= len; i++)
{
p[i] = p[i-1]*P;
h1[i] = h1[i-1]*P+s[i];
}
for(int i = len; i >= 1; i--)
h2[i] = h2[i+1]*P+s[i];
int res = 1;
for(int i = 1; i <= len; i++)//奇数长度回文串
{
int l = 0, r = min(i-1, len-i), ans = 0;
while(l <= r)
{
int m = l+r>>1;
if(h1[i+m]-h1[i-m-1]*p[2*m+1] == h2[i-m]-h2[i+m+1]*p[2*m+1])
{
ans = m;
l = m+1;
}
else
r = m-1;
}
res = max(res, 2*ans+1);
}
for(int i = 1; i <= len-1; i++)//偶数长度回文串
{
if(s[i] != s[i+1])//跳过不合法情况
continue;
int l = 0, r = min(i-1, len-i-1), ans = 0;
while(l <= r)
{
int m = l+r>>1;
if(h1[i+m+1]-h1[i-m-1]*p[2*m+2] == h2[i-m]-h2[i+m+2]*p[2*m+2])
{
ans = m;
l = m+1;
}
else
r = m-1;
}
res = max(res, 2*ans+2);
}
printf("Case %d: %d\n", times, res);
}
return 0;
}