hud 3336 count the string (KMP)
2024-10-20 03:19:32
这道题本来想对了,可是因为hdu对pascal语言的限制是我认为自己想错了,结果一看题解发现自己对了……
- 题意:给以字符串 计算出以前i个字符为前缀的字符中 在主串中出现的次数和
- 如: num(abab)=num(a)+num(ab)+num(aba)+num(abab)=2+2+1+1=6;
- 题解:next[i]记录的是 长度为i 不为自身的最大首尾重复子串长度 num[i]记录长度为next[i]的前缀所重复出现的次数
- 推介一篇博文,非常不错,和本代码解法不一样,但实质上是一样的。
附上代码:
const mo=;
var sum,next:array[..] of longint;
i,j,n,t,ans:longint;
a:array[..] of char;
procedure main;
begin
fillchar(next,sizeof(next),);
readln(n);
readln(a);
next[]:=-;
i:=-;j:=;
while j<n do
if (i=-) or (a[i]=a[j]) then
begin
inc(i);inc(j);next[j]:=i;
end
else i:=next[i];
ans:=;
fillchar(sum,sizeof(sum),);
for i:= to n do inc(sum[next[i]]);
for i:= to n do
ans:=(ans+sum[i]+) mod mo;
writeln(ans);
end;
begin
readln(t);
while t> do
begin
main;
dec(t);
end;
end.
end;
要注意的 hdu不能用ansistring,必须用成array of char 不过读还是可以直接readln(a);
另外再附一个完整的KMP的代码
var i,j,n,m,t:longint;
next,a,b:array[..] of longint;
procedure main;
begin
readln(n,m);
for i:= to n do read(a[i]);readln;
for i:= to m do read(b[i]);
fillchar(next,sizeof(next),);
i:=;j:=;
while j<m do
if (i=) or (b[i]=b[j]) then
begin
inc(i);inc(j);next[j]:=i;
end
else i:=next[i];
i:=;j:=;
while (i<=m) and (j<=n) do
if (i=) 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(-);
end;
begin
readln(t);
while t> do
begin
main;
dec(t);
end;
end.
这里面比较的是数。
最新文章
- Linux LVM逻辑卷配置过程详解
- css3部分选择器整理
- java 网络(socket)
- mac安装redis
- request获取ip数据
- Sqli-labs less 21
- Linux堆内存管理深入分析
- POJ 1091 跳蚤 容斥原理
- jwplayer 网页在线播放插件
- SSO单点登录之跨域问题
- ACM——01排序
- mysql merge table
- cmake 学习笔记(三)
- 了解HTML5和“她”的 API (一)
- Fibonacci数列前n项值的输出(运用递归算法)
- 构造函数与普通函数的区别还有关于“new”操作符的一些原理
- html4与html5的区别及html5的一些新特性
- ES6 new syntax of Default Function Parameters
- 【BZOJ5505】[GXOI/GZOI2019]逼死强迫症(矩阵快速幂)
- Form 表单提交的几种方式
热门文章
- 《WPF程序设计指南》读书笔记——第2章 基本画刷
- shell自定义函数
- Linux下mail/mailx命令发送邮件
- Nested Loop,Sort Merge Join,Hash Join
- 简单加密算法在C#中的实现
- DemoExample
- python学习笔记15(面向对象编程)
- unity脚本的基础语法
- [转载]vs2012中使用Spring.NET报错:Spring.Context.Support.ContextRegistry 的类型初始值设定项引发异常
- HZNU1015: 矩阵排序