DuongNhi99

Ham Z

Mar 10th, 2022
485
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.66 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. string s,t;
  5. int z[1500000];
  6.  
  7. void hamZ(const string &s)
  8. {
  9.     int n = s.size();
  10.     z[0] = 0;
  11.     int l = 0, r = 0;
  12.    
  13.     for (int i = 1; i < n; ++i)
  14.     {
  15.         if (r < i)
  16.         {
  17.             l = r = i;
  18.             while (r < n && s[r-l] == s[r])
  19.                 ++r;
  20.             z[i] = r-l; --r;
  21.         }
  22.         else{
  23.             int k = i - l;
  24.             if (z[k] < r-i+1)
  25.                 z[i] = z[k];
  26.             else {
  27.                 l = i;
  28.                 while (s[r-l] == s[r]) ++r;
  29.                 z[i] = r-l; --r;
  30.             }
  31.         }
  32.     }
  33. }
  34.  
  35. int main()
  36. {
  37.     getline(cin,s);
  38.     getline(cin,t);
  39.     s = t + "#" + s;
  40.    
  41.     hamZ(s);
  42.    
  43.     for (int i = t.size()+1; i < s.size(); ++i)
  44.         if (z[i] >= t.size())
  45.             cout << i-t.size() << ' ';
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment