Time Limit: 15000MS | Memory Limit: 65536K | |
Total Submissions: 13157 | Accepted: 5028 |
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
Source
题意:求一个字符串的最长回文子串
思路:回文串其实就是以一个节点为中间,两端的字符串是相同的。之前的比较字符串相同的Hash函数是以从左到右的顺序,那么这个就再存一个从右到左的字符串的Hash值。对于每一个字符,二分左半子串的长度,分回文串的长度是奇还是偶两种情况。
#include <iostream>
#include <set>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
typedef long long LL;
#define inf 0x7f7f7f7f const int maxn = 1e6 + ;
char s[maxn];
unsigned long long H[maxn], p[maxn], H_rev[maxn]; unsigned long long getH(int i, int j)
{
return H[j] - H[i - ] * p[j - i + ];
} unsigned long long getHrev(int i, int j)
{
return H_rev[i] - H_rev[j + ] * p[j - i + ];
} int main()
{
int cas = ;
p[] = ;
for(int i = ; i < maxn; i++){
p[i] = p[i - ] * ;
}
while(scanf("%s", s + )){
if(strcmp(s + , "END") == ){
break;
}
int n = strlen(s + );
H[] = ;
H_rev[n + ] = ;
for(int i = ; i <= n; i++){
H[i] = H[i - ] * + (s[i] - 'a' + );
}
for(int i = n; i >= ; i--){
H_rev[i] = H_rev[i + ] * + (s[i] - 'a' + );
} int ans = -;
for(int i = ; i <= n; i++){
int ped = min(i - , n - i), pst = ;
while(pst < ped){
int pmid = (pst + ped + ) / ;
//cout<<pmid<<endl;
if(getH(i - pmid, i - ) == getHrev(i + , i + pmid)){
//
pst = pmid;
}
else{
ped = pmid - ;
}
}
//cout<<i<<" "<<pst<<endl;
ans = max(ans, * pst + );
int qed = min(i - , n + - i), qst = ;
while(qst < qed){
int qmid = (qst + qed + ) / ;
if(getH(i - qmid, i - ) == getHrev(i, i + qmid - )){ qst = qmid;
}
else{
qed = qmid - ;
}
}
ans = max(ans, * qst); } printf("Case %d: %d\n", cas++, ans);
} }