G - Number Sequence
Posted 小小超plus
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了G - Number Sequence相关的知识,希望对你有一定的参考价值。
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.
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 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].
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
KMP(看毛片)算法
1 #include <iostream> 2 using namespace std; 3 #include<string.h> 4 #include<set> 5 #include<stdio.h> 6 #include<math.h> 7 #include<queue> 8 #include<map> 9 #include<algorithm> 10 #include<cstdio> 11 #include<cmath> 12 #include<cstring> 13 #include <cstdio> 14 #include <cstdlib> 15 #include<cstring> 16 int a1[10010]; 17 int a[10010],b[1000010]; 18 int t,lena,lenb; 19 void KMPdebiao() 20 { 21 a1[0]=-1; 22 int j=0,k=-1; 23 while(j<lena-1) 24 { 25 if(k==-1||a[j]==a[k]) 26 { 27 j++; 28 k++; 29 a1[j]=k; 30 } 31 else 32 k=a1[k]; 33 } 34 } 35 int KMP() 36 { 37 int j=0; 38 int i=0; 39 KMPdebiao(); 40 while(i<lenb) 41 { 42 43 if(j==-1||a[j]==b[i]) 44 { 45 j++; 46 i++; 47 } 48 else 49 { 50 j=a1[j]; 51 } 52 if(j==lena) 53 return i-lena+1; 54 } 55 return -1; 56 } 57 int main() 58 { 59 cin>>t; 60 int i; 61 while(t--) 62 { 63 cin>>lenb>>lena; 64 memset(a1,0,sizeof(a1)); 65 memset(a,0,sizeof(a)); 66 memset(b,0,sizeof(b)); 67 for(i=0;i<lenb;i++) 68 cin>>b[i]; 69 for(i=0;i<lena;i++) 70 cin>>a[i]; 71 cout<<KMP()<<endl; 72 } 73 return 0; 74 }
以上是关于G - Number Sequence的主要内容,如果未能解决你的问题,请参考以下文章