Advertisement
zhukov000

min_sub_hash

Feb 15th, 2021
730
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4. using LL = long long;
  5. #define fastio ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
  6.  
  7. const int BASE = 1e9 + 7;
  8. const int P = 131;
  9. const int MAXN = 1e5;
  10.  
  11. vector<int> power(2*MAXN + 1, 0);
  12.  
  13. void init_power()
  14. {
  15.   power[0] = 1;
  16.   for(size_t i=1; i<power.size(); ++i)
  17.     power[i] = (1LL * power[i-1] * P) % BASE;
  18. }
  19.  
  20. struct HashString
  21. {
  22.   string val;
  23.   size_t size;
  24.   vector<int> h; // hash-value on prefix
  25.  
  26.   HashString( string pval ): val(pval), size(val.size()), h(size + 1, 0)
  27.   {
  28.     for(size_t i=1; i<=size; ++i)
  29.       h[i] = (h[i-1] + 1LL * val[i-1] * power[i-1]) % BASE;
  30.   }
  31. };
  32.  
  33. void solve()
  34. {
  35.   init_power();
  36.  
  37.   string s;
  38.   cin >> s;
  39.   size_t n = s.size();
  40.   HashString ss(s+s);
  41.  
  42.   int pmn = 0;
  43.   for(size_t k=1; k<n; ++k)
  44.   {
  45.     int pcur = k;
  46.     // binary search equal prefix len
  47.     int left = 0, right = n + 1;
  48.     while (right - left > 1)
  49.     {
  50.       int mid = (left + right) / 2;
  51.       // pmn + mid, pcur + mid - indexes of substring's begin
  52.       int h1 = (ss.h[pmn+mid] - ss.h[pmn] + BASE) % BASE;
  53.       int h2 = (ss.h[pcur+mid] - ss.h[pcur] + BASE) % BASE;
  54.  
  55.       if ( (1LL * h1 * power[pcur-pmn]) % BASE == h2 )
  56.         left = mid;
  57.       else
  58.         right = mid;
  59.     }
  60.  
  61.     if ( left < n )
  62.     {
  63.       if (ss.val[pcur + left] < ss.val[pmn + left])
  64.         pmn = pcur;
  65.     }
  66.   }
  67.   cout << ss.val.substr(pmn, n);
  68. }
  69.  
  70. int main()
  71. {
  72.   fastio
  73.   #ifdef AZHUKOV
  74.   freopen("input.txt", "r", stdin);
  75.   #endif // AZHUKOV
  76.  
  77.   solve();
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement