Advertisement
Guest User

Untitled

a guest
Dec 28th, 2018
1,561
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <ctime>
  2. #include <cstdio>
  3. #include <cstring>
  4. #include <cstdlib>
  5. #include <algorithm>
  6. #include <iostream>
  7. using namespace std;
  8.  
  9. #define begin asdasdasd
  10.  
  11. const int N = 1 << 17;
  12. const int A = 100 + 2;
  13. int n, total, c[N], suf[N], new_c[N], new_suf[N], begin[N], where[N], s[N], pos, x, real_n;
  14. long long res;
  15.  
  16. int safe(int x) {
  17.     return x >= n ? x - n : x;
  18. }
  19.  
  20. void build() {
  21.     memset(begin, 0, sizeof(begin));
  22.     for (int i = 0; i < n; ++i) {
  23.         c[i] = s[i];
  24.         begin[c[i] + 1]++;
  25.         suf[i] = i;
  26.     }
  27.     for (int i = 0; i + 1 < A; ++i)
  28.         begin[i + 1] += begin[i];
  29.     for (int l = 0; l < n; l = (l ? l * 2 : 1)) {
  30.         for (int i = 0; i < n; ++i) {
  31.             pos = safe(suf[i] - l + n);
  32.             new_suf[begin[c[pos]]++] = pos;
  33.         }
  34.         total = 0;
  35.         for (int i = 0; i < n; ++i) {
  36.             if ((i == 0) || (c[new_suf[i - 1]] != c[new_suf[i]]) || (c[safe(new_suf[i - 1] + l)] != c[safe(new_suf[i] + l)]))
  37.                 begin[total++] = i;
  38.             new_c[new_suf[i]] = total - 1;
  39.         }
  40.         memcpy(suf, new_suf, n * sizeof(suf[0]));
  41.         memcpy(c, new_c, n * sizeof(c[0]));
  42.     }
  43. }
  44.  
  45. int main() {
  46.     freopen("towers.in", "r", stdin);
  47.     freopen("towers.out", "w", stdout);
  48.     while ((scanf("%d", &n) == 1) && (n > 0)) {
  49.         for (int i = 0; i < n; ++i)
  50.             scanf("%d", &s[i]), s[i]++, s[n + i] = s[i];
  51.         s[2 * n] = 0, real_n = n, n = 2 * n + 1;
  52.         build();
  53.         for (int i = 0; i < n; ++i)
  54.             where[suf[i]] = i; 
  55.         res = 0;
  56.         for (int i = 0; i < n; ++i)
  57.             if (where[i] == n - 1)
  58.                 x = 0;
  59.             else {
  60.                 while ((x < real_n) && (s[i + x] == s[suf[where[i] + 1] + x]))
  61.                     ++x;
  62.                 if (i < real_n)
  63.                     res += x;
  64.                 x = max(0, x - 1);
  65.             }
  66.         cout << res << endl;
  67.         // printf("%lld\n", res);
  68.     }
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement