Advertisement
newb_ie

Hash Functions

Jul 7th, 2021
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int maxN = 1000;
  5. const int64_t p = 31;
  6. const int64_t m = 1e9 + 9;
  7. int64_t h[maxN],inv[maxN];
  8.  
  9. inline int64_t bin_pow (int64_t a,int64_t b) {
  10.     a %= m;
  11.     int64_t res = 1;
  12.     while (b > 0) {
  13.         if (b & 1) res = res * a % m;
  14.         a = a * a % m;
  15.         b >>= 1;
  16.     }
  17.     return res;
  18. }
  19.  
  20. inline void compute_hash (string & s) {
  21.     int64_t p_pow = 1;
  22.     inv[0] = 1;
  23.     h[0] = s[0] - 'a' + 1;
  24.     for (int i = 1; i < (int) s.size(); ++i) {
  25.         p_pow = (p_pow * p) % m;
  26.         inv[i] = bin_pow(p_pow,m - 2);
  27.         h[i] = (h[i - 1] + (s[i] - 'a' + 1) * p_pow) % m;
  28.     }
  29. }
  30.  
  31. int64_t sub_hash (int l,int r) {
  32.     int64_t res = h[r];
  33.     if (l > 0) res -= h[l - 1];
  34.     res *= inv[l];
  35.     res %= m;
  36.     return res;
  37. }
  38.  
  39. int64_t single_hash (string & s) {
  40.     int64_t hash_value = 0;
  41.     int64_t p_pow = 1;
  42.     for (char c : s) {
  43.         hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m;
  44.         p_pow = (p_pow * p) % m;
  45.     }
  46.     return hash_value;
  47. }
  48.  
  49. int main () {
  50.      ios::sync_with_stdio(false);
  51.      cin.tie(nullptr);
  52.      cout.tie(nullptr);
  53.      int T = 1;
  54.      //~ cin >> T;
  55.      for (int test_case = 1; test_case <= T; ++test_case) {
  56.          string s,start,end;
  57.          cin >> s >> start >> end;
  58.          compute_hash(s);
  59.          int64_t single_start = single_hash(start);
  60.          int64_t single_end = single_hash(end);
  61.          cout << single_start << ' ' << sub_hash(0,1) << '\n';
  62.      }
  63.      //cerr << "Time elapsed :" << clock() * 1000.0 / CLOCKS_PER_SEC << " ms" << '\n';
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement