Advertisement
maxan

Hash

Oct 11th, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. template <const int basis, const int mod>
  2. class Hash {
  3. private:
  4.     int n, _n;
  5.     vector<int> _hash, _powBasis;
  6.  
  7.     int _mod(ll x) {
  8.         return ((x % mod) + mod) % mod;
  9.     }
  10.  
  11.     int _pow(ll x, ll k) {
  12.         if (k == 0) {
  13.             return 1;
  14.         } else if (k == 1) {
  15.             return x;
  16.         } else {
  17.             ll t = _pow(x, k / 2);
  18.  
  19.             return _mod(_mod(t * t) * (k % 2 == 0 ? 1 : x));
  20.         }
  21.     }
  22.  
  23.     void count_n() {
  24.         _n = _pow(basis, (ll)(mod - 2) * (ll)n);
  25.     }
  26.  
  27. public:
  28.     Hash(string &s) {
  29.         n = s.length();
  30.  
  31.         _hash.resize(n + 1);
  32.         _powBasis.resize(n + 1);
  33.  
  34.         _powBasis[0] = 1;
  35.         for (int i = 0; i < n; ++i) {
  36.             _powBasis[i + 1] = _mod((ll)_powBasis[i] * (ll)basis);
  37.         }
  38.  
  39.         _hash[0] = 0;
  40.         for (int i = 0; i < n; ++i) {
  41.             _hash[i + 1] = _mod(_hash[i] + _mod((ll)s[i] * (ll)_powBasis[i]));
  42.         }
  43.  
  44.         count_n();
  45.     }
  46.  
  47.     int getHashSubStr(int l, int r) { // [l, r)
  48.         return _mod((ll)_mod((ll)_mod(_hash[r] - _hash[l]) * (ll)_powBasis[n - l]) * (ll)_n);
  49.     }
  50. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement