newb_ie

String Hashing (Number of Different Substrings)

Jun 11th, 2021 (edited)
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. int single_hash (const string & s) {
  2.     const int p = 31;
  3.     const int m = 1e9 + 9;
  4.     int64_t hash_value = 0;
  5.     int64_t p_pow = 1;
  6.     for (char c : s) {
  7.         hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m;
  8.         p_pow = (p_pow * p) % m;
  9.     }
  10.     return hash_value;
  11. }
  12.  
  13. int compute_hash (const string & s) {
  14.     int n = (int) s.size();
  15.     const int p = 31;
  16.     const int m = 1e9 + 9;
  17.     vector<int64_t> p_pow(n);
  18.     p_pow[0] = 1;
  19.     for (int i= 1; i < n; ++i) p_pow[i] = (p_pow[i - 1] * p) % m;
  20.     vector<int64_t> h(n + 1,0);
  21.     for (int i = 0; i < n; ++i) {
  22.         h[i + 1] = (h[i] + (s[i] - 'a' + 1) * p_pow[i]) % m;
  23.     }
  24.     //number of different substring(for small length)
  25.     int cnt = 0;
  26.     for (int l = 1; l <= n; ++l) {
  27.         set<int64_t> hs;
  28.         for (int i = 0; i <= n - l; ++i) {
  29.             int64_t cur_h = (h[i + l] + m - h[i]) % m;
  30.             cur_h = (cur_h * p_pow[n - i - 1]) % m;
  31.             hs.insert(cur_h);
  32.         }
  33.         cnt += (int) hs.size();
  34.     }
  35.     return cnt;
  36. }
Add Comment
Please, Sign In to add comment