ahmrf

Untitled

Oct 12th, 2015
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int MAXN = 1000010;
  6. const unsigned BASE = 1000000007;
  7. char S[MAXN];
  8. unsigned L[MAXN], P[MAXN];
  9.  
  10. void __gen_pow() {
  11.     P[0] = 1;
  12.     for(int i = 1; i < MAXN; i++) {
  13.         P[i] = P[i - 1] * BASE;
  14.     }
  15. }
  16.  
  17. void __gen_hash(int n) {
  18.     L[0] = S[0];
  19.     for(int i = 1; i < n; i++) {
  20.         L[i] = L[i - 1] * BASE + S[i];
  21.     }
  22. }
  23.  
  24. unsigned __rev_hash(int j) {
  25.     unsigned val = 0;
  26.     for(int i = j; i > -1; i--) {
  27.         val = val * BASE + S[i];
  28.     }
  29. }
  30.  
  31. bool check(int j, int n) {
  32.     unsigned hash_val = __rev_hash(j), val_now;
  33.     int lim = n - j;
  34.     for(int i = 0; i < lim; i++) {
  35.         val_now = L[i + j];
  36.         if(i > 0) {
  37.             val_now = val_now - L[i - 1] * P[j + 1];
  38.         }
  39.         if(val_now == hash_val) {
  40.             return true;
  41.         }
  42.     }
  43.     return false;
  44. }
  45.  
  46. int main() {
  47.     __gen_pow();
  48.     int T;
  49.     scanf("%d\n", &T);
  50.     while(T--) {
  51.         gets(S);
  52.         int n = strlen(S);
  53.         __gen_hash(n);
  54.         int l = n - 1, r = n - 1, ans = 0;
  55.         set<int> st;
  56.         st.insert(l);
  57.         while(1) {
  58.             if(check(l, n)) {
  59.                 ans = max(ans, l);
  60.                 l = (l + r) / 2;
  61.             } else {
  62.                 l /= 2;
  63.             }
  64.             if(st.count(l) > 0) break;
  65.             st.insert(l);
  66.         }
  67.         for(int i = ans; i > -1; i--) {
  68.             putchar(S[i]);
  69.         }
  70.         puts("");
  71.     }
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment