Given two sequences of numbers : a[1], a[2], ...... , a[N], and b[1], b[2], ...... , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make a[K] = b[1], a[K + 1] = b[2], ...... , a[K + M - 1] = b[M]. If there are more than one K exist, output the smallest one.
InputThe first line of input is a number T which indicate the
number of cases. Each case contains three lines. The first line is two
numbers N and M (1 <= M <= 10000, 1 <= N <= 1000000). The
second line contains N integers which indicate a[1], a[2], ...... ,
a[N]. The third line contains M integers which indicate b[1], b[2],
...... , b[M]. All integers are in the range of [-1000000, 1000000].

OutputFor each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.

Sample Input

2
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 1 3
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 2 1

Sample Output

6
-1 首先是预处理Next数组,初始化Next[0]=-1,j=-1 然后从i=0开始,如果j!=-1&&不匹配,j=Next[j]。否则判断p[++i]==p[++j],如果相等,直接让Next[i]=Next[j],不等的话,让Next[i]=j; 然后在主串里匹配。i=0,j=0; j!=-1&&不匹配, j=Next[j]。否则i++,j++
 #include<stdio.h>
#include<string.h>
int Next[],t[],p[];//模式串对应的Next
int n,m,_; void prekmp() {//预处理Next数组
int i,j;
j=Next[]=-;
i=;
while(i<m) {
while(j!=-&&p[i]!=p[j]) j=Next[j];
if(p[++i]==p[++j]) Next[i]=Next[j];//会快一点 博客体现了这一点
else Next[i]=j;
}
} int kmp() {//查找在主串的位置
int i=,j=;
prekmp();
while(i<n&&j<m) {
while(j!=-&&t[i]!=p[j]) j=Next[j];
i++;j++;
}
if(j==m) return i-m+;
else return -;
} int main() {
for(scanf("%d",&_);_;_--) {
scanf("%d%d",&n,&m);
for(int i=;i<n;i++) {
scanf("%d",&t[i]);
}
for(int i=;i<m;i++) {
scanf("%d",&p[i]);
}
int ans=kmp();
printf("%d\n",ans);
}
}

最新文章

  1. Android 自定义title 之Action Bar
  2. CC3000 主机驱动API介绍
  3. ZOJ 3798--解题报告
  4. 判断Featureclass的类型
  5. Spring EL ternary operator (if-then-else) example
  6. c++ string类型转换为char *类型
  7. H5缓存
  8. mysql进阶(十一)外键在数据库中的作用
  9. Redis的java客户端jedis
  10. db2 索引
  11. Loader
  12. 自动化 数据分离 --A文件里面的类 中的函数 调用 B文件里面类 的函数 的方法
  13. centos7下创建mysql5.6多实例
  14. 爬虫学习之-requests乱码
  15. 第一个Windows窗口应用程序
  16. CentOS下Docker与.netcore(一) 之 安装
  17. Android学习——自定义控件(一)
  18. 【Linux】- CentOS搭建FTP服务器
  19. 第十九章:UTC time和local time的互换
  20. Java-API-Package:java.util

热门文章

  1. windows下基于bat的每1分钟执行一次一个程序
  2. 关于play!的attachments.path配置、以及关于Form表单上传请求的认识
  3. centos系统查看本机IP地址
  4. Python_pip_01_pip的相关操作
  5. c语言输入数据
  6. DR客户端一直连接服务器....(6)
  7. 算法Sedgewick第四版-第1章基础-024-M/M/1 queue
  8. 杭电acm刷题(3):1062,Text Reverse 标签: 杭电acm 2017-05-15 08:26 126人阅读 评论(0)
  9. format Code
  10. 使用metasploit进行栈溢出攻击-5