newb_ie

String Hashing

Jul 9th, 2021 (edited)
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. const int maxN = 2100;
  2.  
  3. struct StringHash {
  4. const int64_t p = 31;
  5. const int64_t m = 1e9 + 7;
  6. int64_t h[maxN],inv[maxN];
  7. inline int64_t bin_pow (int64_t a,int64_t b) {
  8. a %= m;
  9. int64_t res = 1;
  10. while (b > 0) {
  11. if (b & 1) res = res * a % m;
  12. a = a * a % m;
  13. b >>= 1;
  14. }
  15. return res;
  16. }
  17. inline void compute_hash (string & s) {
  18. int64_t p_pow = 1;
  19. inv[0] = 1;
  20. h[0] = s[0] - 'a' + 1;
  21. for (int i = 1; i < (int) s.size(); ++i) {
  22. p_pow = (p_pow * p) % m;
  23. inv[i] = bin_pow(p_pow,m - 2);
  24. h[i] = (h[i - 1] + (s[i] - 'a' + 1) * p_pow) % m;
  25. }
  26. }
  27. inline int64_t sub_hash (int l,int r) {
  28. int64_t res = h[r];
  29. if (l > 0) res -= h[l - 1];
  30. res = (res * inv[l]) % m;
  31. if (res < 0) res += m;
  32. return res;
  33. }
  34. inline int64_t single_hash (string & s) {
  35. int64_t hash_value = 0;
  36. int64_t p_pow = 1;
  37. for (int i = 0; i < (int) s.size(); ++i) {
  38. hash_value = (hash_value + (s[i] - 'a' + 1) * p_pow) % m;
  39. p_pow = (p_pow * p) % m;
  40. }
  41. return hash_value;
  42. }
  43. };
Add Comment
Please, Sign In to add comment