题目:
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模板题
代码实现:
1 #include<stdio.h> 2 int a[1000010],b[10010]; 3 int la,lb; 4 void get_next(int b[],int next[]); 5 int kmp(int a[],int b[]); 6 int main() 7 { 8 int i,t,k; 9 scanf("%d",&t); 10 while(t--) 11 { 12 scanf("%d%d",&la,&lb); 13 for(i=0;i<la;i++) 14 scanf("%d",&a[i]); 15 for(i=0;i<lb;i++) 16 scanf("%d",&b[i]); 17 k=kmp(a,b); 18 if(k>=0) 19 printf("%d ",k+1); 20 else//不匹配返回-1 21 printf("-1 "); 22 } 23 return 0; 24 } 25 int kmp(int a[],int b[]) 26 { 27 int i,j; 28 int next[10010]; 29 30 get_next(b,next); 31 i=0; 32 j=0; 33 while(i < la && j < lb) 34 { 35 if(j==-1 || a[i] == b[j]) 36 { 37 i++; 38 j++; 39 } 40 else 41 j=next[j]; 42 } 43 //printf("%d ",i-lb); 44 if(j >= lb) 45 return i-lb;//返回i-匹配串的长度 46 else 47 return -1; 48 } 49 void get_next(int b[],int next[]) 50 { 51 int i,j; 52 i=0; 53 j=-1; 54 next[0]=-1; 55 while(i < lb) 56 { 57 if(j==-1 || b[i] == b[j]) 58 { 59 i++; 60 j++; 61 next[i]=j; 62 } 63 else 64 j=next[j]; 65 } 66 /*for(i=0;i<lb;i++) 67 printf("%d ",next[i]); 68 printf(" ");*/ 69 }