Sicily 1282. Computer Game, sicily1282
Question address: 1282. Computer Game
Ideas:
The KMP algorithm has a lot of information on the Internet. I have learned a lot from some online solutions. Thank you !!!
Let me briefly explain my understanding of the KMP algorithm through this question (Do not spray it, although no one looks at me orz ~~~~ ).
The first input is the string to be matched. If the first letter of the string does not repeat the entire string, it can be directly matched.
Ah, what should we do if we repeat it? Then we can repeat the last repeat, so we can find a good method to optimize the algorithm. The essence of the KMP algorithm is roughly like this.
The code for this question is as follows:
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 5 int main() { 6 int len1, len2; 7 while (cin >> len1) { 8 int code[60001] = {0}; 9 int next[60001] = {0};10 for (int i = 1; i <= len1; i++) {11 scanf("%d", &code[i]);12 }13 int index = 0;14 for (int i = 2; i <= len1; i++) {15 index = code[index+1] == code[i] ? index+1 : 0;16 next[i] = index;17 }18 cin >> len2;19 index = 0;20 int test, result;21 for (int i = 1; i <= len2; i++) {22 scanf("%d", &test);23 if (index != len1) {24 index = code[index+1] == test ? index+1 : next[index];25 if (index == len1) {26 result = i-len1;27 }28 }29 }30 index == len1 ? cout << result << endl : cout << "no solution\n";31 }32 33 return 0;34 }