Cod sursa(job #701152)

Utilizator vergilius_beberindeie virgil vergilius_be Data 1 martie 2012 13:57:59
Problema Potrivirea sirurilor Scor 0
Compilator fpc Status done
Runda Arhiva educationala Marime 1.06 kb
program kmp;{potrivire siruri}
var x,y:string;
pi,d:array[1..1000003] of longint;
i,k,n,m:integer;
f,g:text;
procedure constructie_pi;
var i,k:integer;
begin
  n:=length(x);
  k:=0;
  pi[1]:=0;{pi[i]<i => pi[1]=0}
  for i:=2 to n 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}
         k:=k+1;
     pi[i]:=k;
  end;

end;
begin
   assign(f,'potrivire.in');
   assign(g,'potrivire.out');
   reset(f);
   rewrite(g);
   readln(f,x);
   readln(f,y);
   m:=length(y);
   constructie_pi;
   k:=0;
   for i:=1 to m 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
                           k:=k+1;
        d[i]:=k;
      end;
      for i:=1 to m do
         if (d[i]=n) then
            writeln(g,i-n+1,' ');
   close(f);
   close(g);
end.