bhupixb

Rolling Hash

Mar 20th, 2020
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1.  
  2. // Warning: Change mod and N according to question
  3. const int mod = (1LL << 31)-1;
  4. const int N = 1e6 + 3;
  5.  
  6. #define int long long
  7. #define MP make_pair
  8. #define F first
  9. #define S second
  10. #define sz(s) ((int)s.size())
  11.  
  12. int rand(int l, int r){
  13. static std::mt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count());
  14. std::uniform_int_distribution<int> ludo(l, r); return ludo(rng);
  15. }
  16.  
  17. inline int add(int x, int y, int mod = ::mod) {
  18. x += y;
  19. if (x >= mod or x < 0) x %= mod;
  20. if (x >= 0) return x;
  21. return x + mod;
  22. }
  23. inline int mul(int x, int y, int mod = ::mod) {
  24. if (x >= mod or x + mod < 0) x %= mod;
  25. if (y >= mod or y + mod < 0) y %= mod;
  26. x *= y;
  27. if (x >= mod or x + mod < 0) x %= mod;
  28. if (x >= 0) return x;
  29. return x + mod;
  30. }
  31. inline int sub(int x, int y, int mod = ::mod) {
  32. x -= y;
  33. if (x + mod < 0 or x >= mod) {
  34. x %= mod;
  35. }
  36. if (x >= 0) return x;
  37. return x + mod;
  38. }
  39.  
  40. char s[N];
  41.  
  42. struct Hash {
  43. vector<pair<int,int>> H, pre;
  44. Hash(const char *s, int N, int b1 = 41, int b2 = 53) :
  45. H(N + 5), pre(N + 5) {
  46. pre[0].F = 1, b1 = rand(37, 1 << 10);
  47. pre[0].S = 1, b2 = rand(41, 1 << 9);
  48. int cur1 = 0, cur2 = 0;
  49. for (int i = 1; i <= N; ++i) {
  50. pre[i].F = mul(pre[i-1].F, b1);
  51. pre[i].S = mul(pre[i-1].S, b2);
  52. cur1 = add(mul(cur1, b1), (s[i] - 'a' + 1));
  53. cur2 = add(mul(cur2, b2), (s[i] - 'a' + 1));
  54. H[i].F = cur1, H[i].S = cur2;
  55. }
  56. }
  57. pair<int,int> get_hash(int l, int r) {
  58. int rem1 = mul(pre[r-l+1].F, H[l-1].F);
  59. int rem2 = mul(pre[r-l+1].S, H[l-1].S);
  60. return MP(sub(H[r].F, rem1), sub(H[r].S, rem2));
  61. }
  62. };
Add Comment
Please, Sign In to add comment