Advertisement
Guest User

Untitled

a guest
Jun 14th, 2016
2,987
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. int c = 37;
  2. int mod = 1000*1000*1000+3777;
  3.  
  4. struct hashed_string{
  5.  
  6.     vector<long long> h;
  7.     vector<long long> rh;
  8.     vector<long long> pows;
  9.     int n;
  10.  
  11.     hashed_string(string s){
  12.         n = s.length();
  13.         h.assign(n, 0);
  14.         rh.assign(n, 0);
  15.         pows.assign(n, 1);
  16.         h[0] = s[0]-'a'+1;
  17.         rh[0] = s[n-1]-'a'+1;
  18.         for (int i = 1; i<n; i++){
  19.             pows[i] = (pows[i-1]*c)%mod;
  20.             h[i] = (h[i-1]*c+(s[i]-'a'+1))%mod;
  21.             rh[i] = (rh[i-1]*c+(s[n-1-i]-'a'+1))%mod;
  22.         }
  23.     }
  24.  
  25.     long long get_hash(int l, int r){
  26.         if (l==0){
  27.             return h[r];
  28.         } else {
  29.             return ((h[r]-(h[l-1]*pows[r-l+1]))%mod+mod)%mod;
  30.         }
  31.     }
  32.  
  33.     long long get_reverse_hash(int l, int r){
  34.         if (r==n-1){
  35.              return rh[n-l-1];
  36.         } else {
  37.             return ((rh[n-l-1]-(rh[n-r-2]*pows[r-l+1]))%mod+mod)%mod;
  38.         }
  39.     }
  40.  
  41.     bool is_palindrome(int l, int r){
  42.         if (l==r) return true;
  43.         if ((r-l+1)%2==0){
  44.             return (get_hash(l, (l+r)/2)==get_reverse_hash((l+r)/2+1, r));
  45.         } else {
  46.             return (get_hash(l, (l+r)/2-1)==get_reverse_hash((l+r)/2+1, r));
  47.         }
  48.     }
  49.  
  50. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement