KMP模板

复制代码
 1 var s,t:array[0..2000000]of char;
 2     next:array[0..2000000]of longint;
 3     cas,v,i,n,m,ans:longint;
 4   
 5 procedure getnext;
 6 var i,j:longint;
 7 begin
 8  i:=0; j:=1;
 9  next[1]:=0;
10  while j<=n do
11  begin
12   if (i=0)or(s[i]=s[j]) then
13   begin
14    inc(i); inc(j);
15    next[j]:=i;
16   end
17    else i:=next[i];
18  end;
19 end;
20   
21 procedure kmp;
22 var i,j:longint;
23 begin
24  i:=1; j:=1;
25  while j<=m do
26  begin
27   if (i=0)or(s[i]=t[j]) then
28   begin
29    inc(i); inc(j);
30    if i>n then
31    begin
32     inc(ans);
33     i:=next[i];
34    end;
35   end
36    else i:=next[i];
37   
38  end;
39 end;
40   
41 begin
42   
43  readln(cas);
44  for v:=1 to cas do
45  begin
46   n:=0; m:=0;
47   while not eoln do
48   begin
49    inc(n); read(s[n]);
50   end;
51   readln;
52   while not eoln do
53   begin
54    inc(m); read(t[m]);
55   end;
56   readln;
57   getnext;
58   ans:=0;
59   kmp;
60   writeln(ans);
61  end;
62   
63 end.
复制代码

 

posted on   myx12345  阅读(166)  评论(0编辑  收藏  举报

< 2025年1月 >
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8

导航

统计

点击右上角即可分享
微信分享提示