Number Sequence
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
刚接触kmp还不是很理解,next失效函数
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 int f[10001]; 5 int n,m; 6 int a[1000001],b[10001]; 7 int kmp(int t[],int p[]) 8 { 9 int i=0,j=0; 10 while(i<n&&j<m) 11 { 12 if(j==-1||t[i]==p[j]) 13 { 14 i++; 15 j++; 16 } 17 else 18 j=f[j]; 19 } 20 if(j>=m) 21 return i-m+1; 22 return -1; 23 } 24 void next(int p[]) 25 { 26 int k=-1,j=0; 27 f[0]=-1; 28 while(j<m) 29 { 30 if(k==-1||p[k]==p[j]) 31 { 32 k++; 33 f[++j]=k; 34 } 35 else 36 k=f[k]; 37 } 38 } 39 int main() 40 { 41 int T,i,j; 42 //freopen("in.txt","r",stdin); 43 cin>>T; 44 while(T--) 45 { 46 cin>>n>>m; 47 for(i=0;i<n;i++) 48 cin>>a[i]; 49 for(i=0;i<m;i++) 50 cin>>b[i]; 51 next(b); 52 cout<<kmp(a,b)<<endl; 53 } 54 }