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