Salvens

A

Aug 8th, 2023
969
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.16 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3.  
  4. using namespace std;
  5.  
  6. #define int long long
  7.  
  8. const long long INF = 1e9 + 7;
  9. const int MAXN = 5e4 + 10;
  10. const int N = 1e5 + 10;
  11.  
  12. const int M1 = 1e9 + 123;
  13. const int M2 = 1e9 + 321;
  14. const int P1 = 22811;
  15. const int P2 = 22699;
  16. array<int, MAXN> power1, power2;
  17.  
  18. void init_pow() {
  19.     power1[0] = 1;
  20.     power2[0] = 1;
  21.     for (int i = 1; i < MAXN; ++i) {
  22.         power1[i] = (power1[i - 1] * P1) % M1;
  23.         power2[i] = (power2[i - 1] * P2) % M2;
  24.     }
  25. }
  26.  
  27. void build_hash(string& s, vector<pair<int, int>>& h) {
  28.     int n = s.size();
  29.     h.resize(n + 1);
  30.     h[0].first = 0;
  31.     h[0].second = 0;
  32.  
  33.     for (int i = 0; i < n; ++i) {
  34.         h[i + 1].first = (h[i].first + (s[i] - 'a' + 1) * power1[i]) % M1;
  35.         h[i + 1].second = (h[i].second + (s[i] - 'a' + 1) * power2[i]) % M2;
  36.     }
  37. }
  38.  
  39. pair<int, int> get_hash(string& s) {
  40.     int n = s.size();
  41.     pair<int, int> prev, cur;
  42.     prev = {0, 0};
  43.     for (int i = 0; i < n; ++i) {
  44.         cur.first = (prev.first + (s[i] - 'a' + 1) * power1[i]) % M1;
  45.         cur.second = (prev.second + (s[i] - 'a' + 1) * power2[i]) % M2;
  46.         prev = cur;
  47.     }
  48.     return cur;
  49. }
  50.  
  51. bool is_equal(vector<pair<int, int>>& h_l, vector<pair<int, int>>& h_r, int start1, int start2, int len) {
  52.     pair<int, int> d_l, d_r;
  53.     d_l.first = ((h_l[start1 + len].first - h_l[start1].first + M1) * power1[start2]) % M1;
  54.     d_l.second = ((h_l[start1 + len].second - h_l[start1].second + M2) * power2[start2]) % M2;
  55.  
  56.     d_r.first = ((h_r[start2 + len].first - h_r[start2].first + M1) * power1[start1]) % M1;
  57.     d_r.second = ((h_r[start2 + len].second - h_r[start2].second + M2) * power2[start1]) % M2;
  58.  
  59.     return d_l == d_r;
  60. }
  61.  
  62. signed main() {
  63.     ios_base::sync_with_stdio(false);
  64.     cin.tie(nullptr);
  65.     cout.tie(nullptr);
  66.  
  67.     string a, b;
  68.     cin >> a >> b;
  69.     int n = a.size(), m = b.size();
  70.     if (m > n) {
  71.         return 0;
  72.     }
  73.     vector<pair<int, int>> h_a, h_b;
  74.     init_pow();
  75.     build_hash(a, h_a);
  76.     build_hash(b, h_b);
  77.  
  78.     for (int i = 0; i <= n - m; ++i) {
  79.         if (is_equal(h_a, h_b, i, 0, m)) {
  80.             cout << i << ' ';
  81.         }
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment