hdu1711
来源:互联网 发布:初学美工要会哪些软件 编辑:程序博客网 时间:2024/05/29 12:47
Number Sequence
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 12912 Accepted Submission(s): 5848
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
213 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 1 313 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 2 1
Sample Output
6-1
#include<iostream> #include<cstdio> #include<cstring> using namespace std; const int maxn = 1000005; int a[maxn], b[maxn]; int next1[maxn]; int len1, len2; void getNext(int c[]){ int n = len2; next1[0] = -1; int j = -1; for(int i = 1; i < n; i++){ while(j!=-1&&c[j+1]!=c[i]){ j = next1[j]; } if(c[j+1]==c[i]){ j += 1; } next1[i] = j; } } int kmp(int str1[], int str2[]){ int j = -1; getNext(str2); for(int i = 0; i < len1; i++){ while(j!=-1&&str2[j+1]!=str1[i]){ j = next1[j]; } if(str2[j+1] == str1[i]){ j += 1; } if(j==len2-1){ return i-j+1; } } return -1; } int main(){ // freopen("in.txt", "r", stdin); int n; cin>>n; while(n--){ cin>>len1>>len2; for(int i = 0; i < len1; i++){ scanf("%d",&a[i]); }for(int i = 0; i < len2; i++){scanf("%d",&b[i]);}cout<<kmp(a, b)<<endl; } return 0; }
0 0
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- kmp hdu1711
- hdu1711 kmp
- hdu1711(kmp)
- HDU1711-KMP
- LINUX下gdb调试(转载)
- 从telnet www.baidu.com 80 聊聊我经历过的tcp“三次握手”失败---顺便验证telnet是基于tcp协议的
- poj1503
- ryjrdyj
- 游戏服务器中的日志处理方式之一
- hdu1711
- java(引入一个中间变量,不引入中间变量)交换两个变量的值
- Merge k Sorted Lists -- LeetCode
- 设置ActionBar的背景色
- Java复习笔记2【next()和nextLine()】
- Java的可变参数,参数后面三个点
- 隐藏与封装
- poj1573
- 数据表示__浮点数尾数的下溢处理方法