Advertisement
Saleh127

UVA 1584 / Hashing Rotation

Jun 19th, 2022
939
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. /***
  2.  created: 2022-06-19-23.41.40
  3. ***/
  4.  
  5. #include <bits/stdc++.h>
  6. #include <ext/pb_ds/assoc_container.hpp>
  7. #include <ext/pb_ds/tree_policy.hpp>
  8. using namespace std;
  9. using namespace __gnu_pbds;
  10. template<typename U> using ordered_set=tree<U, null_type,less<U>,rb_tree_tag,tree_order_statistics_node_update>;
  11. #define ll long long
  12. #define ull unsigned long long
  13. #define test int tt; cin>>tt; for(int cs=1;cs<=tt;cs++)
  14. #define get_lost_idiot return 0
  15. #define nl '\n'
  16.  
  17. ull p[200005];
  18. ull hash1[200005];
  19. ull rhash1[200005];
  20. ull base=307;
  21.  
  22. void power()
  23. {
  24.     p[0]=1;
  25.     for(int i=1;i<=200003;i++)
  26.     {
  27.         p[i]=p[i-1]*base;
  28.     }
  29. }
  30.  
  31. void hashing(string a)
  32. {
  33.     hash1[0]=0;
  34.     for(int i=1; i<=a.size(); i++)
  35.     {
  36.         hash1[i]=(hash1[i-1]*base+a[i-1]);
  37.     }
  38.  
  39.     rhash1[a.size()+1]=0;
  40.     for(int i=a.size(); i>=1;i--)
  41.     {
  42.         rhash1[i]=(rhash1[i+1]*base + a[i-1]);
  43.     }
  44. }
  45.  
  46. ull forwardhash(ll l,ll r)
  47. {
  48.     return (hash1[r] - (hash1[l-1] * p[r-l+1]));
  49. }
  50.  
  51. ull backwardhash(ll l,ll r)
  52. {
  53.     return (rhash1[l] - (rhash1[r+1] * p[r-l+1]));
  54. }
  55.  
  56. int main()
  57. {
  58.     ios_base::sync_with_stdio(0);
  59.     cin.tie(0);
  60.     cout.tie(0);
  61.  
  62.     power();
  63.  
  64.     test
  65.     {
  66.         ll n,m,i,j,k,l,h;
  67.  
  68.         string a;
  69.  
  70.         cin>>a;
  71.  
  72.         n=a.size();
  73.  
  74.         a+=a;
  75.  
  76.         hashing(a);
  77.  
  78.         k=1;
  79.  
  80.         for(i=2;i<=n;i++)
  81.         {
  82.              l=0,h=n-1;
  83.  
  84.              while(l<=h)
  85.              {
  86.                   ll mid=(l+h)/2;
  87.  
  88.                   if(forwardhash(k,k+mid)==forwardhash(i,i+mid))
  89.                   {
  90.                        l=mid+1;
  91.                   }
  92.                   else
  93.                   {
  94.                        h=mid-1;
  95.                   }
  96.              }
  97.  
  98.              if(l<=n-1)
  99.              {
  100.                   if(a[i+l-1]<a[k+l-1])
  101.                   {
  102.                        k=i;
  103.                   }
  104.              }
  105.         }
  106.  
  107.         cout<<a.substr(k-1,n)<<nl;
  108.  
  109.     }
  110.  
  111.     get_lost_idiot;
  112. }
  113.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement