Advertisement
Guest User

C(hash)

a guest
Jan 19th, 2020
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int mod = 1e9 + 7;
  6.  
  7. long long bin_pow(int a, int n, int m = mod)
  8. {
  9.     if(n == 0)
  10.         return 1;
  11.     if(n == 1)
  12.         return a;
  13.  
  14.     long long t = bin_pow(a, n / 2, m);
  15.     return (((t * t) % m) * (n % 2 ? a : 1)) % m;
  16. }
  17.  
  18. int main()
  19. {
  20.     // Ускорение ввода
  21.     ios_base::sync_with_stdio(0);
  22.     cin.tie(0);
  23.     cout.tie(0);
  24.  
  25.     // Ввод/вывод из файла
  26.     freopen("input.txt", "r", stdin);
  27.     freopen("output.txt", "w", stdout);
  28.  
  29.     // Ввод
  30.     string s;
  31.     cin >> s;
  32.     int n = s.size();
  33.  
  34.     //hash
  35.     long long hash[n + 1], rhash = 0;
  36.     hash[0] = 0;
  37.     for(int i = 1; i <= n; i++)
  38.     {
  39.         hash[i] = (hash[i - 1] + ((s[i - 1] - 'a' + 1) * bin_pow(29, i)) % mod) % mod;
  40.         rhash = (rhash + ((s[i - 1] - 'a' + 1) * bin_pow(29, n - i + 1)) % mod) % mod;
  41.     }
  42.     if(rhash == hash[n])
  43.     {
  44.         cout << "";
  45.         return 0;
  46.     }
  47.     string ans;
  48.     long long suf_hash = 0;
  49.     for(int i = 1; i <= n; i++)
  50.     {
  51.         rhash = (rhash * 29) % mod;
  52.         suf_hash = (suf_hash * 29) % mod;
  53.         suf_hash = (suf_hash + ((s[i - 1] - 'a' + 1) * bin_pow(29, n + 1)) % mod) % mod;
  54.         ans.push_back(s[i - 1]);
  55.         if((rhash + hash[i]) % mod == (hash[n] + suf_hash) % mod)
  56.         {
  57.             reverse(ans.begin(), ans.end());
  58.             cout << ans;
  59.             exit(0);
  60.         }
  61.     }
  62.  
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement