Advertisement
smatskevich

LNIP_Seminar1

Feb 12th, 2022
1,042
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. const int a = 31;
  6. const int simple = 1000000009;
  7.  
  8. typedef long long ll;
  9.  
  10. int my_hash_simple(const std::string& s) {
  11.   if (s.empty()) return 0;
  12.   return s[0];
  13. }
  14.  
  15. int my_hash(const std::string& s, int d) {
  16.   if (s.empty()) return 0;
  17.   ll result = 0;
  18.   for (char c : s) {
  19.     result = (result * a % d + c) % d;
  20.   }
  21.   return int(result);
  22. }
  23.  
  24. void FillPrefixHashes(const std::string& s, std::vector<int>& hashes) {
  25.   int hash = 0;
  26.   hashes.resize(s.size());
  27.   int a_in_power_i = 1;
  28.   for (int i = 0; i < s.size(); ++i) {
  29.     hashes[i] = hash = (hash + s[i] * a_in_power_i) % simple;
  30.     a_in_power_i = a_in_power_i * a % simple;
  31.   }
  32. }
  33.  
  34. int main() {
  35.   std::string s;
  36.   s = "abbabaabbaababba";
  37.  
  38.   std::cout << s.c_str() << std::endl;
  39.   std::cout << my_hash(s, simple) << std::endl;
  40.  
  41.   std::vector<int> hashes;
  42.   FillPrefixHashes(s, hashes);
  43.   return 0;
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement