[USACO 1.3.3] Calf Flac

来源:互联网 发布:office2017 mac 威锋 编辑:程序博客网 时间:2024/05/22 08:21

[题目描述]

Calf Flac

据说如果你给无限只母牛和无限台巨型便携式电脑(有非常大的键盘),那么母牛们会制造出世上最棒的回文。你的工作就是去这些牛制造的奇观(最棒的回文)。在寻找回文时不用理睬那些标点符号、空格(但应该保留下来以便做为答案输出),只用考虑字母'A'-'Z'和'a'-'z'。要你寻找的最长的回文的文章是一个不超过20,000个字符的字符串。我们将保证最长的回文不会超过2,000个字符(在除去标点符号、空格之前)。

PROGRAM NAME: calfflac

INPUT FORMAT

一个不超过20,000个字符的文件。

SAMPLE INPUT (file calfflac.in)

Confucius say: Madam, I'm Adam.

OUTPUT FORMAT

输出的第一行应该包括找到的最长的回文的长度。
下一个行或几行应该包括这个回文的原文(没有除去标点符号、空格),
把这个回文输出到一行或多行(如果回文中包括换行符)。
如果有多个回文长度都等于最大值,输出那个前出现的。

SAMPLE OUTPUT (file calfflac.out)

11
Madam, I'm Adam


[解题思路]

很模型的【最长回文串】,有点小恶心,主要是换行符不能忽略。

以前打的最长回文串都是NlogN的字符串Hash,不过还有更优的Manacher算法,可以O(N)的出解。

Manacher算法相关,请移步这里。


[Code]

{ID: zane2951PROG: calfflacLANG: PASCAL}program calfflac;var   p,r:array[0..211111] of longint;   s,ss:ansistring;   len,i,lim,now,ce,t,ans:longint;//----------min------------function min(a,b:longint):longint;begin   if a<b then exit(a) else exit(b);end;//----------main-----------begin   assign(input,'calfflac.in'); reset(input);   assign(output,'calfflac.out'); rewrite(output);   s:='';   while not seekeof do      begin         readln(ss);         if s<>'' then s:=s+'~'+ss else s:=ss;      end;   len:=length(s);   ss:='#'; t:=1; p[1]:=1;   for i:=1 to len do      begin         ce:=ord(s[i]);         if (ce>=65) and (ce<=90) then            begin ss:=ss+s[i]+'#'; inc(t); p[t]:=i; inc(t); p[t]:=i; end               else if (ce>=97) and (ce<=122) then                  begin ss:=ss+upcase(s[i])+'#'; inc(t); p[t]:=i;inc(t); p[t]:=i; end;      end;   lim:=0; now:=0;   for i:=1 to t do      begin         if lim>i then r[i]:=min(r[now<<1-i],lim-i) else r[i]:=1;         while (i-r[i]>0) and (i+r[i]<=t) do            if (ss[i-r[i]]=ss[i+r[i]]) then inc(r[i]) else break;         if r[i]+i>lim then            begin               lim:=r[i]+i;               now:=i;            end;      end;   ce:=-1;   for i:=1 to t do if r[i]>ce then begin ce:=r[i]; ans:=i; end;   dec(ce);   writeln(ce);   for i:=p[ans-ce+1] to p[ans+ce] do if s[i]='~' then writeln else write(s[i]);   writeln;   close(input); close(output);end.