Number Sequence

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 17971    Accepted Submission(s): 7854

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.
 
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
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN=;
int a[MAXN],b[MAXN],next[MAXN];
int lena,lenb;
void getnext()
{
int i=,j=-;
next[]=-;
while(i<lenb)
{
if(j==-||b[i]==b[j])
{
i++;
j++;
next[i]=j;
}
else j=next[j];
}
}
int KMP()
{
getnext();
int i=,j=;
while(i<lena&&j<lenb)
{
if(j==-||a[i]==b[j])
{
i++;
j++;
}
else j=next[j];
}
if(j==lenb) return i-j+;
else return -;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
memset(next,,sizeof(next));
scanf("%d%d",&lena,&lenb);
for(int i=;i<lena;i++)
scanf("%d",&a[i]);
for(int i=;i<lenb;i++)
scanf("%d",&b[i]);
printf("%d\n",KMP());
} return ;
}
 

最新文章

  1. Python安装pywinauto时遇到error: The read operation timed out解决方法
  2. Lambda表达式演变
  3. 详解js变量、作用域及内存
  4. Sqli-labs less 40
  5. 编写php拓展实例--slime项目(用户登录会话类)
  6. quartus II 自动生成testbench
  7. HTML中标签和元素的区别
  8. DevExpress GridControl 列中显示图片
  9. ASP.NET MVC 几种 Filter 的执行过程源码解析
  10. iOS界面调试工具 Reveal-备用
  11. ServletContext加入和访问
  12. ExtJs--12--Ext定义类的requires uses singleton 三个配置项的使用
  13. Ajax练习题
  14. C#WinCE程序(.NET Compact Framework 3.5)项目重构面向抽象设计
  15. 第六周助教工作总结——NWNU李泓毅
  16. 【转】在Linux下安装python3
  17. 优化实现Mobile/Bumped Diffuse
  18. Python网络编程-Socket简单通信(及python实现远程文件发送)
  19. 洛谷P4072 [SDOI2016]征途(带权二分,斜率优化)
  20. Python 文件 flush() 方法

热门文章

  1. PS 基础知识 .pat文件如何使用
  2. 网站无法显示logo?
  3. css-装饰
  4. LeetCode120——Triangle
  5. centos6.4中文输入法安装和切换(转载)
  6. EasyDarwin接入ffmpeg实现264转图片快照功能
  7. EasyDarwin开发出类似于美拍、秒拍的短视频拍摄SDK:EasyVideoRecorder
  8. 程序员必知的8大排序(java实现)
  9. Qt笔记之使用设计器自定义窗口标题栏
  10. tornado安全应用之用户认证