Time Limit: 15000MS | Memory Limit: 65536K | |
Total Submissions: 12616 | Accepted: 4769 |
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
C/C++:
#include <map>
#include <queue>
#include <cmath>
#include <vector>
#include <string>
#include <cstdio>
#include <cstring>
#include <climits>
#include <iostream>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
const int MAX = 3e6 + ; char my_str[MAX], my_temp[MAX];
int my_len1, my_len2, my_ans[MAX]; void manacher()
{
int my_right = , my_mid = ;
for (int i = ; i < my_len2; ++ i)
{
if (my_right > i) my_ans[i] = min(my_right - i, my_ans[(my_mid << ) - i]);
else my_ans[i] = ;
while (my_temp[i - my_ans[i]] == my_temp[i + my_ans[i]]) my_ans[i] ++;
if (my_right < my_ans[i] + i)
{
my_right = my_ans[i] + i;
my_mid = i;
}
}
} int main()
{
int t = ;
while (scanf("%s", my_str), strcmp(my_str, "END"))
{
my_len1 = strlen(my_str);
my_temp[] = '$';
my_temp[] = '#';
for (int i = , j = ; i < my_len1; ++ i, j += )
{
my_temp[j] = my_str[i];
my_temp[j + ] = '#';
} my_len2 = (my_len1 << ) + ;
my_temp[my_len2] = '*'; manacher();
int temp = ;
for (int i = ; i < my_len2; ++ i)
if (temp < my_ans[i]) temp = my_ans[i];
printf("Case %d: %d\n", t ++, temp - );
} return ;
}