Cod sursa(job #701424)

Utilizator vergilius_beberindeie virgil vergilius_be Data 1 martie 2012 15:50:38
Problema Potrivirea sirurilor Scor 0
Compilator fpc Status done
Runda Arhiva educationala Marime 1.11 kb
program kmp;{potrivire siruri}
var x,y:ansistring;
pi,d:array[1..1000003] of longint;
i,k,n,m:integer;
f,g:text;
procedure constructie_pi;
var i,k:integer;
begin

  k:=0;
  pi[1]:=0;{pi[i]<i => pi[1]=0}
  for i:=2 to m do
  begin
     while (k>0) and (x[i]<>x[k+1]) do {cat timp prefixul nu este nul si literele}
          k:=pi[k];                 {nu coincid sar din K in Pi[K]}
     if (x[i]=x[k+1]) then {daca literele coincid}
         inc(k);
     pi[i]:=k;
  end;

end;
begin
   assign(f,'potrivire.in');
   assign(g,'potrivire.out');
   reset(f);
   rewrite(g);
   readln(f,x);
   readln(f,y);
   n:=length(y);
   m:=length(x);
   constructie_pi;
   k:=0;
   for i:=1 to n do
      begin
        while (k>0) and (y[i]<>x[k+1]) do{cat timp prefixul nu este nul si literele}
                   k:=pi[k];{nu coincid sar din K in Pi[K]}
        if y[i]=x[k+1] then
                           inc(k);
        d[i]:=k;
        if k=m then
          k:=pi[k];

      end;
      for i:=1 to n do
         if (d[i]=m) then
            writeln(g,i-m,' ');
   close(f);
   close(g);
end.