Given two sequences of numbers : a11, a22, ...... , aNN, and b11, b22, ...... , bMM(1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make aKK = b11, aK+1K+1 = b22, ...... , aK+M−1K+M−1 = bMM. 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 a11, a22, ...... , aNN. The third line contains M integers which indicate b11, b22, ...... , bMM. All integers are in the range of −1000000,1000000−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
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
using namespace std;
#define MAXN 1000001
typedef long long LL;
/*
KMP 查找子串首次出现的位置
*/
int s[MAXN],t[MAXN],Next[MAXN];
void kmp_pre(int m)
{
int j,k;
j=;k=-;Next[]=-;
while(j<m)
{
if(k==-||t[j]==t[k])
Next[++j] = ++k;
else
k = Next[k];
}
}
int KMP(int n,int m)
{
int i,j,ans;
i=j=ans=;
kmp_pre(m);
if(n==&&m==)
return (s[]==t[])?:-;
for(i=;i<n;i++)
{
while(j>&&s[i]!=t[j])
j = Next[j];
if(s[i]==t[j])
j++;
if(j>=m)
{
if(i-m+>)
return i-m+;
else
return -;
}
}
return -;
}
int main()
{
int T,n,m;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(int i=;i<n;i++)
scanf("%d",&s[i]);
for(int i=;i<m;i++)
scanf("%d",&t[i]);
printf("%d\n",KMP(n,m));
}
}
 

最新文章

  1. [转]Asp.Net Core 简单的使用加密的Cookie保存用户状态
  2. Asp.net mvc返回Xml结果,扩展Controller实现XmlResult以返回XML格式数据
  3. 基于Lattice_CPLD/FPGA Diamond 开发流程
  4. Android 中 Internal Storage 和 External Storage 的区别
  5. struts2笔记4
  6. Spring-2-B Save the Students(SPOJ AMR11B)解题报告及测试数据
  7. WordPress Backdoor未授权访问漏洞和信息泄露漏洞
  8. Understanding the Android Life Cycle
  9. mybatis dao无实现类的配置
  10. eclipse频繁崩溃退出
  11. vedio_note_1
  12. eclipse注释模板设置(未整理)
  13. openssl基本原理 + 生成证书 + 使用实例
  14. IIS 发布ASP.NET MVC 4.0 错误500.21解决办法
  15. Linux下的计划任务at,batch,crontab
  16. 设计模式学习--Builder
  17. Linux普通用户使用sudo免输密码(Debian/Redhat通用)
  18. Flash Memory 简介【转】
  19. 【C语言】十六进制形式输出应用程序
  20. C# 如何防止重放攻击(转载)

热门文章

  1. 数据库登陆失败原因: 未与信任 SQL Server 连接相关联
  2. 327 Count of Range Sum 区间和计数
  3. 消息队列 (2) java实现简单的RabbtMQ
  4. unity3d 各键值对应代码
  5. kickstart配置文件详解和system-config-kickstart (转载)
  6. java网络
  7. codeforces_724C_Ray Tracing
  8. js弹开页面并调用方法
  9. 如何在mac里面,把xcode代码同步到 tfs 的 git库(新git库)
  10. Linux下/var/log/btmp文件