Problem Description
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.
 
Input
The 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].
 
Output
For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.
 
 
这是一道对kmp算法的最基础运用,在这里主要注意kmp函数以及得到next的函数的写法
 
代码如下:
 #include <iostream>
#include <cstdio>
using namespace std; int n,m;
int a[],b[],next[]; void getnext (int *s,int *next){
next[]=next[]=;
for (int i=;i<m;i++){
int j=next[i];
while (j&&s[i]!=s[j])
j=next[j];
if(s[i]==s[j]) next[i+]=j+;
else next[i+]=;
}
} int kmp (int *a,int *b,int *next){
getnext (b,next);
int j=;
for (int i=;i<n;i++){
while (j&&a[i]!=b[j])
j=next[j];
if (a[i]==b[j])
j++;
if (j==m)
return i-m+;
}
return -;
} int main (){
int t;
scanf ("%d",&t);
while (t--){
scanf ("%d %d",&n,&m);
for (int i=;i<n;i++)
scanf ("%d",&a[i]);
for (int i=;i<m;i++)
scanf ("%d",&b[i]);
int ans=kmp (a,b,next);
printf ("%d\n",ans);
}
return ;
}

最新文章

  1. .net 面试基础题
  2. MySQL学习记录--生成时间日期数据
  3. IOS 应用生命周期
  4. (转)js的左右滑动触屏事件
  5. python3爬虫初探(五)之从爬取到保存
  6. LA 2797 (平面直线图PLSG) Monster Trap
  7. java.io.File类
  8. NodeJS + Socket.io搭建聊天服务器
  9. PHP 生命周期,Opcode 缓存。
  10. js数组,字符串常用方法汇总(面试必备)
  11. Python开发目录
  12. 笔记:Spring Cloud Eureka 服务发现与消费
  13. 设计模式之外观模式——Java语言描述
  14. 【原创】大数据基础之Airflow(1)简介、安装、使用
  15. phpstorm 报错及解决
  16. 《Android进阶之光》--Material Design
  17. C#WinForm应用程序中嵌入ECharts图表
  18. Centos6环境下CI(CodeIgniter)框架创建定时任务
  19. Node.js是用来干嘛的
  20. Linux之Vim学习

热门文章

  1. C++ &lt;string&gt; 里面的size_type
  2. 动手实现 React-redux(二):结合 context 和 store
  3. P1615 西游记公司
  4. 代码文件导到word里
  5. [转]FaceBook ATC 弱网测试工具环境搭建
  6. android控件之webview和js与java交互
  7. 无法登录phpmyadmin,报1130错误
  8. JDBC优化策略总结
  9. js单线程和js异步操作的几种方法
  10. flask_第一个程序