最长回文

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 17251    Accepted Submission(s): 6351

Problem Description
给出一个只由小写英文字符a,b,c...y,z组成的字符串S,求S中最长回文串的长度.
回文就是正反读都是一样的字符串,如aba, abba等
 
Input
输入有多组case,不超过120组,每组输入为一行小写英文字符a,b,c...y,z组成的字符串S
两组case之间由空行隔开(该空行不用处理)
字符串长度len <= 110000
 
Output
每一行一个整数x,对应一组case,表示该组case的字符串中所包含的最长回文长度.
 
Sample Input
aaaa

abab

 
Sample Output
4
3
 
Source
 
Recommend
lcy   |   We have carefully selected several similar problems for you:  1358 1686 3065 1711 3067 
 

题解:

manacher算法的裸体

AC代码:

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
#define N 2000100
int p[N];
char s[N],S[N];
int manacher(int len){
int ans=,id=,mx=;
for(int i=;i<len;i++){
p[i]=mx>i?min(p[id+id-i],mx-i):;
while(S[i-p[i]]==S[i+p[i]]) p[i]++;
if(i+p[i]>mx) mx=i+p[i],id=i;
ans=max(ans,p[i]-);
}
return ans;
}
void deal(int len){
int l=;
S[l++]='$';S[l++]='#';
for(int i=;i<len;i++) S[l++]=s[i],S[l++]='#';
S[l++]='\0';
}
int main(){
//freopen("sh.txt","r",stdin);
while(scanf("%s",s)==){
memset(S,,sizeof S);
memset(p,,sizeof p);
int len=strlen(s);
deal(len);
printf("%d\n",manacher(len+len+));
//fill(S,S+len+len+2,0);
//fill(p,p+len+len+2,0);
}
return ;
}

A2:

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
#define N 210100
int p[N],l;
char s[N],S[N];
int manacher(){
int ans=,mx=-,id=-;
for(int i=;i<=l;i++){
if(id+mx>=i) p[i]=min(p[(id<<)-i],id+mx-i);
while(i-p[i]->=&&i+p[i]+<=l&&S[i-p[i]-]==S[i+p[i]+]) p[i]++;
if(i+p[i]>id+mx) mx=p[i],id=i;
ans=max(ans,p[i]);
}
return ans;
}
int main(){
while(scanf("%s",s)==){
memset(S,,sizeof S);
memset(p,,sizeof p);
int len=strlen(s);
l=-;
for(int i=;i<len;i++) S[++l]='#', S[++l]=s[i];
S[++l]='#';
printf("%d\n",manacher());
}
return ;
}
05-11 15:05