Pagini recente » Cod sursa (job #2625) | Cod sursa (job #1344032) | Cod sursa (job #815720) | Cod sursa (job #1244930) | Cod sursa (job #701424)
Cod sursa(job #701424)
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.