hdu, KMP algorithm, linear string search algorithm, a nice reference provided
2024-09-30 17:26:31
reference:
Rabin-Karp and Knuth-Morris-Pratt Algorithms By TheLlama– TopCoder Member https://www.topcoder.com/community/data-science/data-science-tutorials/introduction-to-string-searching-algorithms/
// to be improved
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 1000005
#define MAXM 10005
int nums[MAXN];
int cnums[MAXM];
int ffunc[MAXM]={0};
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int T,n,m,i,j,k, res;
int *p,*pend, *q, *r, *rend;
if(scanf("%d",&T)!=1) return -1;
while(T-->0 && scanf("%d%d",&n,&m)==2 && n>=m && m>0) {
for(i=1;i<=n;++i) scanf("%d",&nums[i]);
for(i=1;i<=m;++i) scanf("%d",&cnums[i]);
for(i=2;i<=m;++i) {
for(j=ffunc[i-1];;j=ffunc[j]) {
if(cnums[j+1]==cnums[i] || j==0 && --j) break;
}
ffunc[i]=j+1;
}
for(i=1, k=0;;) {
if(nums[i]==cnums[k+1]) { ++k; }
else if(k>0) { k=ffunc[k]; continue; }
if(++i>n || k>=m) break;
}
res=k!=m?-1:i-m;
printf("%d\n",res);
}
return 0;
}
最新文章
- 转载:《TypeScript 中文入门教程》 2、枚举
- XML.04-dom4j和XPath
- c#自动关闭 MessageBox 弹出的窗口
- 【leetcode】Dungeon Game
- 【转】crontab定时任务中文乱码问题
- [转载]ExtJs4 笔记(5) Ext.Button 按钮
- 【CodeForces 602B】G - 一般水的题2-Approximating a Constant Range
- 通过新浪ip地址库获得用户的省份、城市等信息
- linux@64 获取时间的性能评估
- XSS 简单理解之:AntiSamy
- 经验分享:CSS浮动(float,clear)通俗讲解 太棒了,清晰明了
- Java 5种字符串拼接方式性能比较。
- 20170410 --- Linux备课资料 --- vim的使用
- spring AOP知识点总结以及日志的输出
- python中 函数名加括号与不加括号
- Cracking The Coding Interview4.8
- input全选与单选(把相应的value放入隐藏域去)
- JDBC之 连接池
- BZOJ2944 : [Poi2000]代码
- koa学习笔记