Poj2406 KMP Algorithm

Source: Internet
Author: User

Poj2406

Restatement: Given the string S0, record the s0s0 .. S0 consisting of consecutive k s and connected to S0 ^ K. Input the string s to obtain the maximum K so that S = S0 ^ K.

Problem Analysis:

1. Use the KMP algorithm to obtain the prefix function prefix [I] (I = 1, 2,... n, n = length (s )).

2. If n-Prefix [N] can be divisible by N, S can be expressed as K = N/(n-Prefix [N]) consecutive S0, and K obtains the maximum value at this time.

3. Otherwise, s cannot be expressed as a continuous S0, k = 1.

AC code:

 1 //Memory: 5680K        Time: 313MS 2 #include <iostream> 3 #include <cstring> 4 #include <string> 5  6 using namespace std; 7  8 const int maxn = 1000010; 9 10 int prefix[maxn];11 string s;12 13 void init()14 {15     int l = s.size();16     memset(prefix, 0, sizeof(prefix));17     int k = 0;18     for (int i = 2; i <= l; i++) {19         while (k > 0 && s[k] != s[i - 1])20             k = prefix[k];21         if (s[k] == s[i - 1])22             k++;23         prefix[i] = k;24     }25 }26 27 int main()28 {29     while (cin >> s && s != ".") {30         init();31         int l = s.size();32         33         if ( prefix[l] != 0 && l % (l - prefix[l]) == 0) 34             cout << l / (l - prefix[l]) << endl;35         else36             cout << "1" << endl;37     }38     return 0;39 }

 

Poj2406 KMP Algorithm

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.