Advertisement
Guest User

RabinKarp

a guest
Dec 11th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.     string s = "the", t = "We implement the algorithm";
  11.  
  12.     const int  p = 31;
  13.     vector<long long> p_pow(max(s.size(), t.size()));
  14.  
  15.     p_pow[0] = 1;
  16.  
  17.     for (size_t i = 1; i<p_pow.size(); ++i) p_pow[i] = p_pow[i - 1] * p; //
  18.     for (size_t i = 0; i<p_pow.size(); ++i) cout << p_pow[i] << endl;
  19.  
  20.     vector<long long> h(t.size());
  21.     for (size_t i = 0; i<t.size(); ++i)
  22.     {
  23.         h[i] = (t[i] - 'a' + 1) * p_pow[i];
  24.         if (i)  h[i] += h[i - 1];
  25.     }
  26.  
  27.     for (size_t i = 1; i<h.size(); ++i) cout << endl << h[i];
  28.  
  29.     long long h_s = 0;
  30.     for (size_t i = 0; i<s.size(); ++i) h_s += (s[i] - 'a' + 1) * p_pow[i];
  31.  
  32.     cout << endl << h_s << endl;
  33.  
  34.     for (size_t i = 0; i + s.size() - 1 < t.size(); ++i)
  35.     {
  36.         long long cur_h = h[i + s.length() - 1];
  37.         if (i)  cur_h -= h[i - 1];
  38.         if (cur_h == h_s * p_pow[i])
  39.             cout << i << ' ';
  40.     }
  41.  
  42.     return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement