Advertisement
smatskevich

Seminar11

Apr 21st, 2022
1,244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. std::vector<int> PrefixFunction(const std::string& s) {
  6.   std::vector<int> pi(s.size());
  7.   for (int i = 1; i < s.size(); ++i) {
  8.     for (int j = pi[i - 1]; j > 0; j = pi[j - 1]) {
  9.       if (s[i] == s[j]) {
  10.         pi[i] = j + 1;
  11.         break;
  12.       }
  13.     }
  14.     if (pi[i] == 0 && s[i] == s[0]) pi[i] = 1;
  15.   }
  16.   return pi;
  17. }
  18.  
  19. int main0() {
  20.   std::string s;
  21.   std::cin >> s;
  22.   std::vector<int> pi = PrefixFunction(s);
  23.   for (int v : pi) std::cout << v << " ";
  24.   std::cout << std::endl;
  25.   return 0;
  26. }
  27.  
  28. std::vector<int> ZFunction(const std::string& s) {
  29.   std::vector<int> z(s.size());
  30.   z[0] = s.size();
  31.   int l = 0, r = 0;
  32.   for (int i = 1; i < s.size(); ++i) {
  33.     if (i < r) {
  34.       z[i] = std::min(r - i, z[i - l]);
  35.     }
  36.     while (i + z[i] < s.size() && s[z[i]] == s[i + z[i]]) ++z[i];
  37.     if (i + z[i] > r) {
  38.       l = i;
  39.       r = i + z[i];
  40.     }
  41.   }
  42.   return z;
  43. }
  44.  
  45. int main() {
  46.   std::string s;
  47.   std::cin >> s;
  48.   std::vector<int> pi = ZFunction(s);
  49.   for (int v : pi) std::cout << v << " ";
  50.   std::cout << std::endl;
  51.   return 0;
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement