hud 3336 count the string (KMP)

时间:2014-06-06 17:30:22   收藏:0   阅读:227

这道题本来想对了,可是因为hdu对pascal语言的限制是我认为自己想错了,结果一看题解发现自己对了……

附上代码:

bubuko.com,布布扣
const mo=10007;
var sum,next:array[0..200000] of longint;
    i,j,n,t,ans:longint;
    a:array[0..200000] of char;
procedure main;
 begin
 fillchar(next,sizeof(next),0);
 readln(n);
 readln(a);
 next[0]:=-1;
 i:=-1;j:=0;
 while j<n do
  if (i=-1) or (a[i]=a[j]) then
   begin
    inc(i);inc(j);next[j]:=i;
   end
  else i:=next[i];
 ans:=0;
 fillchar(sum,sizeof(sum),0);
 for i:=1 to n do inc(sum[next[i]]);
 for i:=1 to n do
  ans:=(ans+sum[i]+1) mod mo;
 writeln(ans);
 end;
begin
 readln(t);
 while t>0 do
  begin
   main;
   dec(t);
  end;
end.
 end;
bubuko.com,布布扣

要注意的 hdu不能用ansistring,必须用成array of char 不过读还是可以直接readln(a);

另外再附一个完整的KMP的代码

bubuko.com,布布扣
var i,j,n,m,t:longint;
    next,a,b:array[0..1000100] of longint;
procedure main;
 begin
 readln(n,m);
 for i:=1 to n do read(a[i]);readln;
 for i:=1 to m do read(b[i]);
 fillchar(next,sizeof(next),0);
 i:=0;j:=1;
 while j<m do
  if (i=0) or (b[i]=b[j]) then
   begin
    inc(i);inc(j);next[j]:=i;
   end
  else i:=next[i];
 i:=1;j:=1;
 while (i<=m) and (j<=n) do
  if (i=0) or (b[i]=a[j]) then
   begin
   inc(i);inc(j);
   end
  else i:=next[i];
 if i>m then writeln(j-m)
 else writeln(-1);
 end;
begin
 readln(t);
 while t>0 do
  begin
  main;
  dec(t);
  end;
end.
bubuko.com,布布扣

这里面比较的是数。

hud 3336 count the string (KMP),布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!