Advertisement
smatskevich

Seminar11

Apr 24th, 2023
761
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. std::vector<int> Prefix(const std::string& s) {
  5.   std::vector<int> pi(s.size());
  6.   int prev_pi = 0;
  7.   for (size_t i = 1; i < s.size();) {
  8.     if (s[i] == s[prev_pi]) {
  9.       pi[i] = ++prev_pi;
  10.       ++i;
  11.     } else if (prev_pi == 0) {
  12.       pi[i] = 0;
  13.       ++i;
  14.     } else {
  15.       prev_pi = pi[prev_pi - 1];
  16.     }
  17.   }
  18.   return pi;
  19. }
  20.  
  21. std::vector<int> ZFunction(const std::string& s) {
  22.   std::vector<int> z(s.size());
  23.   z[0] = s.size();
  24.   int l = 0, r = 0;
  25.   for (int i = 1; i < s.size(); ++i) {
  26.     if (i >= r) {
  27.       while (i + z[i] < s.size() && s[z[i]] == s[i + z[i]]) ++z[i];
  28.       l = i;
  29.       r = i + z[i];
  30.     } else {
  31.       if (z[i - l] < r - i) z[i] = z[i - l];
  32.       else if (z[i - l] > r - i) z[i] = r - i;
  33.       else {
  34.         z[i] = z[i - l];
  35.         while (i + z[i] < s.size() && s[z[i]] == s[i + z[i]]) ++z[i];
  36.         l = i;
  37.         r = i + z[i];
  38.       }
  39.     }
  40.   }
  41.   return z;
  42. }
  43.  
  44. std::vector<int> ZFunction2(const std::string& s) {
  45.   std::vector<int> z(s.size());
  46.   z[0] = s.size();
  47.   int l = 0, r = 0;
  48.   for (int i = 1; i < s.size(); ++i) {
  49.     if (i < r) {
  50.       z[i] = std::min(z[i - l], r - i);
  51.     }
  52.     while (i + z[i] < s.size() && s[z[i]] == s[i + z[i]]) ++z[i];
  53.     if (i + z[i] > r) {
  54.       l = i;
  55.       r = i + z[i];
  56.     }
  57.   }
  58.   return z;
  59. }
  60.  
  61. int main() {
  62.   std::string s; std::cin >> s;
  63. //  auto pi = Prefix(s);
  64.   auto z = ZFunction2(s);
  65.   for (int x : z) std::cout << x;
  66.   return 0;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement