到底有沒有大大能夠用KMP AC了呢?
如果有的話,那我下面的程式碼又到底錯了什麼呢?
我吃了很多TLE的說@@
謝謝
(pascal版)
type a=array[1..20] of integer;
var string_set:array[1..10000] of string;b:a;
i,cnt,n,run:integer;exist:boolean;
str:string; function compute_prefix(s:string):a;
var len,k,q:integer;tem:a;
begin
len:=length(s);
tem[1]:=0;
k:=0;
for q:= 2 to len do
begin
while ((k>0) and (s[k+1]<>s[q])) do k:=tem[k];
if s[k+1]=s[q] then inc(k);
tem[q]:=k;
end;
compute_prefix:=tem;
end;
function KMP(s,f:string):boolean;
var found:boolean;len_s,len_f,i1,q:integer;
begin
len_s:=length(s);
len_f:=length(f);
q:=0;
found:=false;
if len_s>=len_f then
for i1:= 1 to len_s do
begin
while ((q>0) and (f[q+1]<>s[i1])) do q:=b[q];
if f[q+1]=s[i1] then inc(q);
if q=len_f then begin found:=true;break;end;
end;
KMP:=found;
end;
begin
while not eof do
begin
readln(n);cnt:=0;
for run:= 1 to n do
begin
readln(str);
exist:=false;
b:=compute_prefix(str);
for i:= 1 to cnt do
begin
exist:=KMP(string_set[i],str);
if exist then break;
end;
if exist then writeln('Old! ',i)
else begin inc(cnt);string_set[cnt]:=str; writeln('New! ',cnt);end;
end;
end;
end.
KMP 只是用於單一字串比對
若是多字串比對建議用AC tree / suffix array / Trie 均可