poj 3461 Oulipo KMP算法

题目:给出一个单词w和一篇文章t,求该单词在文章中出现了多少次(可以有重叠部分)。

分析:很裸的KMP算法,现求出w的next数组,再进行匹配,匹配次数即为答案。

下面附程序:

var
  w,t:ansistring;
  lenw,lent,i,n,j,l,ans:longint;
  next:array[0..10000] of longint;

procedure get;
var
  i,j:longint;
begin
  next[0]:=-1;
  next[1]:=0;
  i:=2;
  j:=0;
  while i<=lenw do
    if (j=-1)or(w[j+1]=w[i])
      then begin
             inc(j);
             next[i]:=j;
             inc(i);
           end
      else j:=next[j];
end;

begin
  readln(n);
  for l:=1 to n do
  begin
    readln(w);
    readln(t);
    lenw:=length(w);
    lent:=length(t);
    get;
    ans:=0;
    i:=1;
    j:=0;
    while i<=lent do
    begin
      if (j=-1)or(w[j+1]=t[i])
        then begin
               inc(j);
               inc(i);
             end
        else j:=next[j];
      if j=lenw then
      begin
        inc(ans);
        j:=next[j]; 
      end;
    end;
    writeln(ans);
  end;
end.


你可能感兴趣的:(poj 3461 Oulipo KMP算法)