[KMP] Number Sequence, kmpnumbersequence
KMP Algorithm
The basic topic of kmp and the application of the kmp algorithm of the number array.
This mainly refers to the processing of pattern strings. When there are duplicates in a pattern string, the pattern string traces the position of the duplicate point to the left (next []).
Problem DescriptionGiven 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,100 0000]. outputFor each test case, you shoshould 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
Source HDU 2007-Spring Programming Contest 1 # include <stdio. h> 2 int a [1000001], B [10001], next [10001]; 3 void getnext (int m) {4 int I = 1, j = 0; 5 next [1] = 0; 6 while (I <m) {7 if (j = 0 | B [I] = B [j]) {8 I ++; j ++; next [I] = j; 9} 10 else j = next [j]; 11} 12} 13 14 void getk (int n, int m) {15 int I = 1, j = 1; 16 while (I <= n & j <= m) {17 if (j = 0 | a [I] = B [j]) {I ++; j ++;} 18 else j = next [j]; 19} 20 if (j> m) printf ("% d \ n", I-m); 21 else printf ("-1 \ n "); 22} 23 24 int main () 25 {26 int t, n, m, I, j; 27 scanf ("% d", & t); 28 while (t --) {29 scanf ("% d", & n, & m); 30 for (I = 1; I <= n; I ++) scanf ("% d", & a [I]); 31 for (I = 1; I <= m; I ++) scanf ("% d ", & B [I]); 32 getnext (m); 33 getk (n, m); 34} 35 return 0; 36}View Code