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;
}

最新文章

  1. 转载:《TypeScript 中文入门教程》 2、枚举
  2. XML.04-dom4j和XPath
  3. c#自动关闭 MessageBox 弹出的窗口
  4. 【leetcode】Dungeon Game
  5. 【转】crontab定时任务中文乱码问题
  6. [转载]ExtJs4 笔记(5) Ext.Button 按钮
  7. 【CodeForces 602B】G - 一般水的题2-Approximating a Constant Range
  8. 通过新浪ip地址库获得用户的省份、城市等信息
  9. linux@64 获取时间的性能评估
  10. XSS 简单理解之:AntiSamy
  11. 经验分享:CSS浮动(float,clear)通俗讲解 太棒了,清晰明了
  12. Java 5种字符串拼接方式性能比较。
  13. 20170410 --- Linux备课资料 --- vim的使用
  14. spring AOP知识点总结以及日志的输出
  15. python中 函数名加括号与不加括号
  16. Cracking The Coding Interview4.8
  17. input全选与单选(把相应的value放入隐藏域去)
  18. JDBC之 连接池
  19. BZOJ2944 : [Poi2000]代码
  20. koa学习笔记

热门文章

  1. 【C语言】控制台窗口图形界面编程(一)句柄和文本属性
  2. http和socket
  3. ionic提供的配色方案
  4. 算法竞赛入门经典5.2 STL初步
  5. 使用枚举(emum)代替常量类
  6. [Python3网络爬虫开发实战] 1.9.2-Scrapyd的安装
  7. 基于html实现一个todolist待办事项
  8. C语言《一维数组的学习,冒泡排序》
  9. Online IDE &amp; Public URLs &amp; turbo
  10. hihoCoder#1077 RMQ问题再临-线段树