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