Closing ideas: KMP standard template questions, note that there are two versions of KMP, the advantages and disadvantages here have been reflected in the code
1 #include <iostream> 2 #include <cstring> 3 #include <string> 4 #include <algorithm> 5 using namespace std; 6 7 int a[1000100]; 8 int b[10100]; 9 int Len_a, Len_b; 10 int Next[10100] 11 ; 12 void GetNext() 13 { 14 int i = 0, j = Next[0] = -1; 15 while (i < Len_b) 16 { 17 //Version 1 18 if (j == -1 || b[i] == b[j]) 19 Next[++i] = ++j; 20 /* 21 22 Version 2: 23 if (j == -1 || b[i] == b[j]) 24 { 25 i++; 26 j++; 27 Next[i] = (b[i] == b[j] ? Next[j] : j) 28 } 29 Compared with the non-improved next[] table, the calculation time of the next[] table itself is a little slower, but the average length of jumps when KMP is matched is slightly larger. 30 31 After construction, a next[] table is only used once and does not reflect the advantages. If a pattern string is to be matched against many strings, the improved next[] construction time is trivial, and the matching speed is reflected. 32 */ 33 else 34 j = Next[j]; 35 } 36 } 37 38 int KMP() 39 { 40 int i = 0 , j = 0 ; 41 GetNext(); 42 while (i < Len_a && j < Len_b ) 43 { 44 if (j == - 1 || a[i] == b[j]) 45 { 46 i++; 47 j++; 48 } 49 else 50 j = Next[j]; 51 } 52 53 if (j == Len_b) 54 return i - j + 1; 55 else 56 return -1; 57 } 58 59 int main(void) 60 { 61 ios::sync_with_stdio(false); 62 63 int cas; 64 cin >> cas; 65 while (cas--) 66 { 67 cin >> Len_a >> Len_b; 68 for (int i = 0; i < Len_a; ++i) 69 cin >> a[i]; 70 71 for (int j = 0; j < Len_b; ++j) 72 cin >> b[j]; 73 74 cout << KMP() << endl; 75 } 76 77 return 0; 78 }