Number Sequence
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9058 Accepted Submission(s): 4149
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算法,已经略懂
AC代码:
1 #include<stdio.h> 2 int a[1000005], b[10005]; 3 int fail[10005]; 4 int n, m, T; 5 void getfail() 6 { 7 fail[0] = -1; 8 int i, j; 9 for(i = 1, j = -1; i < m; i ++) 10 { 11 while(j >= 0 && b[j + 1] != b[i]) 12 { 13 j = fail[j]; 14 } 15 if(b[j + 1] == b[i]) 16 j ++; 17 fail[i] = j; 18 } 19 return ; 20 } 21 22 int kmp() 23 { 24 getfail(); 25 int i, j; 26 for(i = 0, j = 0; i < n;i ++) 27 { 28 while(j && b[j] != a[i]) 29 { 30 j = fail[j - 1] + 1; 31 } 32 if(b[j] == a[i]) 33 j ++; 34 if(j == m) 35 return i - m + 2; 36 } 37 return -1; 38 } 39 40 int main(int argc, char const *argv[]) 41 { 42 scanf("%d", &T); 43 int i, j; 44 while(T--) 45 { 46 scanf("%d%d", &n, &m); 47 for(i = 0; i < n; i ++) 48 scanf("%d", &a[i]); 49 for(i = 0; i < m; i ++) 50 scanf("%d", &b[i]); 51 getfail(); 52 printf("%d ", kmp()); 53 } 54 return 0; 55 }