Advertisement
ke_timofeeva7

структура хэшей

Oct 11th, 2021
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. using namespace std;
  2.  
  3. const int N = 1000009;
  4.  
  5. struct Hash
  6. {
  7.     int h1, h2;
  8.  
  9.     Hash(int x, int y) : h1(x), h2(y) {}
  10.     Hash(int x) : h1(x), h2(x) {}
  11.     Hash() : h1(0), h2(0) {}
  12. };
  13.  
  14. const Hash P = { 31, 37 }, MOD = { (int)1e9 + 7, (int)1e9 + 9 };
  15.  
  16. vector<Hash> pw(N);
  17.  
  18. Hash operator + (Hash a, Hash b)
  19. {
  20.     return { (a.h1 + b.h1) % MOD.h1, (a.h2 + b.h2) % MOD.h2 };
  21. }
  22.  
  23. Hash operator - (Hash a, Hash b)
  24. {
  25.     return { (a.h1 - b.h1 + MOD.h1) % MOD.h1, (a.h2 - b.h2 + MOD.h2) % MOD.h2 };
  26. }
  27.  
  28. Hash operator * (Hash a, Hash b)
  29. {
  30.     return { (a.h1 * b.h1) % MOD.h1, (a.h2 * b.h2) % MOD.h2 };
  31. }
  32.  
  33. Hash operator % (Hash a, Hash b)
  34. {
  35.     return { a.h1 % b.h1, a.h2 % b.h2 };
  36. }
  37.  
  38. Hash operator * (Hash a, int b)
  39. {
  40.     return { (a.h1 * b) % MOD.h1, (a.h2 * b) % MOD.h2 };
  41. }
  42.  
  43. bool operator != (Hash a, Hash b)
  44. {
  45.     return a.h1 != b.h1 || a.h2 != b.h2;
  46. }
  47.  
  48. bool operator == (Hash a, Hash b)
  49. {
  50.     return a.h1 == b.h1 && a.h2 == b.h2;
  51. }
  52.  
  53. void build_powers()
  54. {
  55.     pw[0] = 1;
  56.  
  57.     for (int i = 1; i < N; i++)
  58.     {
  59.         pw[i] = pw[i - 1] * P;
  60.     }
  61.  
  62.     return;
  63. }
  64.  
  65. vector<Hash> build_hash(string s)
  66. {
  67.     vector<Hash> hs((int)s.size());
  68.     hs[0] = 0;
  69.  
  70.     for (int i = 1; i < (int)s.size(); i++)
  71.     {
  72.         hs[i] = hs[i - 1] + pw[i] * s[i];
  73.     }
  74.  
  75.     return hs;
  76. }
  77.  
  78. Hash get_hash(vector<Hash>& hs, int l, int r)
  79. {
  80.     return hs[r] - hs[l - 1];
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement