Advertisement
rafikamal

Suffix Array

Dec 8th, 2013
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. struct Entry {
  2.     int first;
  3.     int second;
  4.     int p;
  5.    
  6.     bool operator <(const Entry& e) const {
  7.         return (first == e.first ? second < e.second : first < e.first);
  8.     }
  9. } L[SIZE];
  10.  
  11. int P[MAX_LOG][SIZE];
  12. int LCP[SIZE];
  13. int step;
  14. int B[SIZE];
  15.  
  16. bool comp(const int& a, const int& b) {
  17.     return P[step - 1][a] < P[step - 1][b];
  18. }
  19.  
  20. void suffixArray(string &str) {
  21.     int i, cnt;
  22.    
  23.     for (i = 0; i < str.size(); i++)
  24.         P[0][i] = str[i] - 'a';
  25.        
  26.     for (step = 1, cnt = 1; (cnt>>1) < str.size(); step++, cnt <<= 1) {
  27.         for (i = 0; i < str.size(); i++) {
  28.             L[i].first = P[step - 1][i];
  29.             L[i].second = (i + cnt < str.size() ? P[step - 1][i + cnt] : -1);
  30.             L[i].p = i;
  31.         }
  32.        
  33.         sort(L, L + str.size());
  34.        
  35.         for (i = 0; i < str.size(); i++) {
  36.             P[step][L[i].p] =
  37.                 (i > 0 && L[i].first == L[i - 1].first && L[i].second == L[i - 1].second
  38.                     ? P[step][L[i - 1].p] : i);
  39.         }
  40.     }
  41.    
  42.     for (i = 0; i < str.size(); i++)
  43.         B[i] = i;
  44.     sort(B, B + str.size(), comp);
  45.    
  46.     for (i = 1; i < str.size(); i++) {
  47.         int k;
  48.         int x = B[i];
  49.         int y = B[i - 1];
  50.        
  51.         LCP[i] = 0;
  52.         for (k = step - 1; k >= 0 && x < str.size() && y < str.size(); k--) {
  53.             if (P[k][x] == P[k][y]) {
  54.                 x += 1 << k;
  55.                 y += 1 << k;
  56.                 LCP[i] += 1 << k;
  57.             }
  58.         }
  59.     }
  60.    
  61.     /*for (i = 0; i < str.size(); i++)
  62.         cout << B[i] << " : " << LCP[i] << endl;*/
  63. }
  64.  
  65. int main()
  66. {
  67.     int tc, t, x, y, z, d;
  68.     int i, j, k, l, h, n, m;
  69.     char ch; double P;
  70.     string str, str1, str2;
  71.    
  72. #ifndef ONLINE_JUDGE
  73.     freopen("input.txt", "r", stdin);
  74.     //freopen("output.txt", "w", stdout);
  75. #endif
  76.    
  77.     ios_base::sync_with_stdio(false);
  78.    
  79.     cin >> str;
  80.     suffixArray(str);
  81.    
  82.     int total = 0;
  83.     for (i = 0; i < str.size(); i++)
  84.         total += (str.size() - B[i] - LCP[i]);
  85.     cout << total << endl;
  86.    
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement