Poj1961
Repeat the problem:
Enter a string s with a length of L to obtain the prefix of all s consisting of repeated strings, and output the length of the prefix and the maximum repetition of the prefix.
AC code:
1 //Memory: 5700K Time: 641MS 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 int n;30 int case_num = 1;31 while (cin >> n && n) {32 cin >> s;33 init();34 int l = s.size();35 cout << "Test case #" << case_num++ << endl;36 for (int k = 1; k <= l; k++) {37 if ( prefix[k] != 0 && k % (k - prefix[k]) == 0) {38 cout << k << " " << k / (k - prefix[k]) << endl;39 }40 }41 cout << endl;42 }43 return 0;44 }
Poj1961 KMP Algorithm