Simpsons' Hidden Talents hdu2594 kmp

来源:互联网 发布:华为端口聚合配置 编辑:程序博客网 时间:2024/05/18 21:49

Description


Homer: Marge, I just figured out a way to discover some of the talents we weren’t aware we had.
Marge: Yeah, what is it?
Homer: Take me for example. I want to find out if I have a talent in politics, OK?
Marge: OK.
Homer: So I take some politician’s name, say Clinton, and try to find the length of the longest prefix
in Clinton’s name that is a suffix in my name. That’s how close I am to being a politician like Clinton
Marge: Why on earth choose the longest prefix that is a suffix???
Homer: Well, our talents are deeply hidden within ourselves, Marge.
Marge: So how close are you?
Homer: 0!
Marge: I’m not surprised.
Homer: But you know, you must have some real math talent hidden deep in you.
Marge: How come?
Homer: Riemann and Marjorie gives 3!!!
Marge: Who the heck is Riemann?
Homer: Never mind.
Write a program that, when given strings s1 and s2, finds the longest prefix of s1 that is a suffix of s2.

Solution


一开始连题目都看错了,如果只是求b串最长的前缀同时是a串的子串的话就是傻逼题了

已知next[i]表示1..next[i]与i-next[i]+1..i完全相等,那么把两个字符串连起来对自己求next,next[strlen(str)]就是答案了

字符串来自c++的恶意

Code


var  nex:array[0..100001]of longint;  a,b:ansistring;procedure getNex;var  i,j:longint;begin  nex[1]:=0;  j:=0;  for i:=2 to length(a) do  begin    while (a[i]<>a[j+1])and(j>0) do j:=nex[j];    if (a[i]=a[j+1]) then inc(j);    nex[i]:=j;  end;  if nex[length(a)]>length(a)-length(b) then nex[length(a)]:=length(a)-length(b);  if nex[length(a)]>length(b) then nex[length(a)]:=length(b);  if nex[length(a)]>0 then  write(copy(a,1,nex[length(a)]),' ');  writeln(nex[length(a)]);end;begin  while not eof do  begin    readln(a);    readln(b);    a:=a+b;    getNex;  end;end.
1 0
原创粉丝点击