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