KMP算法模板(pascal)

洛谷P3375:

 1 program rrr(input,output);
 2 var
 3   i,j,lena,lenb:longint;
 4   a,b:ansistring;
 5   next:array[0..1010]of longint;
 6 begin
 7    assign(input,'r.in');assign(output,'r.out');reset(input);rewrite(output);
 8    readln(a);
 9    readln(b);
10    lena:=length(a);lenb:=length(b);
11    next[1]:=0;
12    for i:=2 to lenb do
13        begin
14           j:=next[i-1];
15           while (b[i]<>b[j+1]) and (j>0) do j:=next[j];
16           if b[i]=b[j+1] then next[i]:=j+1 else next[i]:=0;
17        end;
18    j:=0;
19    for i:=1 to lena do
20        begin
21           while (a[i]<>b[j+1]) and (j>0) do j:=next[j];
22           if a[i]=b[j+1] then inc(j) else j:=0;
23           if j=lenb then writeln(i-lenb+1);
24        end;
25    for i:=1 to lenb do write(next[i],' ');
26    close(input);close(output);
27 end.

 

posted @ 2017-02-10 19:53  Klaier  阅读(313)  评论(0编辑  收藏  举报