HDU 1711 Number Sequence (KMP模板)
来源:互联网 发布:海康监控软件 编辑:程序博客网 时间:2024/06/03 07:23
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 <string.h>#include <iostream>#include <cstdio>#define maxn 1000010int next[maxn];int n,m;void getNext(int* P, int* f){ f[0] = 0; f[1] = 0; for(int i = 1; i < m; i++) { int j = f[i]; while(j && P[i] != P[j]) { j = f[j]; } f[i + 1]=P[i]==P[j]?j+1:0; }}int kmp(int* T, int* P, int*f){ getNext(P, f); int j = 0; for(int i = 0; i < n; i++) { while(j && P[j] != T[i]) { j = f[j]; } if(P[j] == T[i]) { j++; } if(j == m) { return i-m+2; } } return -1;}int main(){ int s1[maxn]; int s2[maxn]; int a; int t; scanf("%d",&t); while(t--) {scanf("%d%d",&n,&m); if(m>n) { puts("-1"); continue; } for(int i=0;i<n;i++) { scanf("%d",&s1[i]); } for(int i=0;i<m;i++) { scanf("%d",&s2[i]); } int a=kmp(s1,s2,next); printf("%d\n",a); } return 0;}
- [KMP模板题]HDU-1711 Number Sequence
- HDU - 1711 Number Sequence (KMP模板)
- 【KMP模板】HDU 1711 Number Sequence
- Kmp 模板 之 hdu 1711 Number Sequence
- HDU 1711 Number Sequence(KMP模板)
- hdu 1711 Number Sequence KMP模板题~~~
- hdu 1711 Number Sequence KMP模板题
- hdu 1711 Number Sequence(kmp模板题)
- HDU 1711Number Sequence(KMP模板)
- hdu 1711Number Sequence(kmp模板题)
- hdu 1711 Number Sequence KMP模板题
- HDU 1711 Number Sequence(kmp模板)
- HDU 1711 Number Sequence(KMP 模板)
- HDU 1711 Number Sequence(KMP模板)
- hdu 1711 Number Sequence kmp模板
- HDU 1711 Number Sequence【KMP模板】
- 【hdu 1711】 Number Sequence KMP模板
- 模板 kmp算法 hdu 1711 Number Sequence
- ImagerLoader缓存到SdCard
- Android性能优化(下)
- Centos安装FastDFS集群文件系统
- Javascript字符串单引号与双引号的区别
- python 文件头的编码声明问题
- HDU 1711 Number Sequence (KMP模板)
- JS当中的拷贝!!!
- Oracle学习日志
- 欢迎使用CSDN-markdown编辑器
- D3.js学习笔记十五:D3.js树图(Tree)展开和折叠
- 二进制 与十进制 互相转换
- 国家代码
- 测试代码运行后不报错,数据库也会生成表,但控制台不能输出。哪位大神能帮我解决?
- composer 安装yii2框架