题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1686
kmp裸题
网上kmp的解法很多,讲了一大通很复杂的样子,偶然看到一股清流,很好懂,很清楚,写法有点变通,但更容易理解记忆
%%%matrix67 传送门
贴代码
var p:array[0..1000005]of longint;
a,b:array[0..1000005]of char;
s1,s2:ansistring;
n,m,Q,t,ans:longint;
procedure pre;
var i,j:longint;
begin
fillchar(p,sizeof(p),0);
j:=0;
for i:=2 to n do
begin
while(j>0)and(a[j+1]<>a[i])do j:=p[j];
if a[j+1]=a[i] then inc(j);
p[i]:=j;
end;
end;
procedure work;
var i,j:longint;
begin
readln(s1);readln(s2);
n:=length(s1);m:=length(s2);
for i:=1 to n do a[i]:=s1[i];
for i:=1 to m do b[i]:=s2[i];
pre;ans:=0;
j:=0;
for i:=1 to m do
begin
while (j>0)and(a[j+1]<>b[i]) do j:=p[j];
if a[j+1]=b[i] then inc(j);
if j=n then begin
inc(ans);
j:=p[j];
end;
end;
writeln(ans);
end;
begin
// assign(input,'1686.in');reset(input);
// assign(output,'1686.out');rewrite(output);
readln(Q);
for t:=1 to Q do work;
// close(input);close(output);
end.
【写的有漏洞的,欢迎路过大神吐槽】
2017/09/05 23:34:12
Ending.