Sicily 1282. Computer Game, sicily1282

Source: Internet
Author: User

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 } 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.