【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】
2009 Multi-University Training Contest 16 - Host by NIT
【Solution】
Manacher算法求最长回文。
代码如下:
var ans:longint;
s:ansistring;
p:array[0..300050] of longint;
st:array[0..300050] of char;
function min(x,y:longint):longint; begin if x<y then exit(x) else exit(y); end;
procedure work();
var i,mx,id,l:longint;
begin
for i:=1 to length(s) do begin
st[i*2-1]:='#'; st[i*2]:=s[i];
end; l:=length(s)*2+1;
st[0]:='&'; st[l]:='#'; st[l+1]:='%';
mx:=0;
for i:=1 to l do begin
if mx>i then p[i]:=min(p[2*id-i],mx-i) else p[i]:=1;
while st[i+p[i]]=st[i-p[i]] do inc(p[i]);
if i+p[i]>mx then begin mx:=i+p[i]; id:=i; end;
end;
ans:=0;
for i:=1 to l do if p[i]-1>ans then ans:=p[i]-1;
end;
begin
while not eof do begin
readln(s); readln;
work(); writeln(ans);
end;
end.