DuongNhi99

HASH

Dec 17th, 2020
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define int64_t long long
  3. using namespace std;
  4.  
  5. const int N = 1005;
  6. const int P = 311;
  7. const int BASE = 1000000007LL;
  8.  
  9. string s, t;
  10. int n, m;
  11. int64_t Pow[N];
  12. int64_t A[N], B[N];
  13.  
  14. void hash_build(string s, int n, int64_t Hash[]) {
  15.    for(int i = 1; i <= n; ++i)
  16.       Hash[i] = (Hash[i-1] * P + s[i-1]) % BASE;
  17. }
  18.  
  19. int64_t hash_range(int L, int R, int64_t Hash[]) {
  20.    return (Hash[R] - Hash[L - 1] * Pow[R - L + 1] + 1LL * BASE * BASE) % BASE;
  21. }
  22.  
  23. int main() {
  24.    freopen("in.txt", "r", stdin);
  25.    //freopen("Hash.inp", "r", stdin);
  26.    //freopen("Hash.out", "w", stdout);
  27.    ios_base::sync_with_stdio(false);
  28.    cin.tie(0); cout.tie(0);
  29.  
  30.    Pow[0] = 1;
  31.    for(int i = 1; i <= N; ++i)
  32.       Pow[i] = (Pow[i-1] * P) % BASE;
  33.  
  34.    cin >> s >> t;
  35.    n = s.size();
  36.    m = t.size();
  37.  
  38.    hash_build(s, n, A);
  39.    hash_build(t, m, B);
  40.  
  41.    for(int i = 1; i <= n - m + 1; ++i) {
  42.       int l = i, r = i + m - 1;
  43.       if(hash_range(l, r, A) == B[m])
  44.          cout << i << ' ';
  45.    }
  46.  
  47.    return 0;
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment