Advertisement
cosenza987

Untitled

Apr 14th, 2024 (edited)
600
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. //Слава Україні, Героям слава
  2.  
  3. #include <bits/stdc++.h>
  4.  
  5. using namespace std;
  6.  
  7. const int N = 2e5 + 7, alph = 26, L = 20;
  8.  
  9. char s[N];
  10. int len[N], link[N], to[alph][N], par[N], sze[N], nxt[N], up[L][N];
  11. int n, last, sz, ans;
  12.  
  13. void init() {
  14.     memset(len, 63, sizeof(len));
  15.     memset(nxt, -1, sizeof(nxt));
  16.     s[n++] = -1;
  17.     link[0] = 1;
  18.     len[0] = 0;
  19.     len[1] = -1;
  20.     sz = 2;
  21.     for(int i = 0; i < N; i++) {
  22.         par[i] = i;
  23.         sze[i] = 1;
  24.     }
  25. }
  26.  
  27. int find(int a) {
  28.     return par[a] == a ? a : par[a] = find(par[a]);
  29. }
  30.  
  31. bool unite(int a, int b) {
  32.     if((a = find(a)) == (b = find(b))) return false;
  33.     if(sze[a] < sze[b]) swap(a, b);
  34.     sze[a] += sze[b];
  35.     par[b] = a;
  36.     return true;
  37. }
  38.  
  39. int get_link(int v) {
  40.     while(s[n - len[v] - 2] != s[n - 1]) v = link[v];
  41.     return v;
  42. }
  43.  
  44. void add_letter(char c, int ind) {
  45.     s[n++] = c;
  46.     last = get_link(last);
  47.     if(!to[c - 'a'][last]) {
  48.         len[sz] = len[last] + 2;
  49.         link[sz] = to[c - 'a'][get_link(link[last])];
  50.         to[c - 'a'][last] = sz++;
  51.         last = to[c - 'a'][last];
  52.         up[0][last] = link[last];
  53.         for(int i = 1; i < L; i++) {
  54.             up[i][last] = up[i - 1][up[i - 1][last]];
  55.         }
  56.         int cur = last;
  57.         for(int i = L - 1; i >= 0; i--) {
  58.             if(len[up[i][cur]] > (len[last] + 1) / 2) {
  59.                 cur = up[i][cur];
  60.             }
  61.         }
  62.         nxt[last] = up[0][cur];
  63.     } else {
  64.         last = to[c - 'a'][last];
  65.     }
  66.     int cur = last;
  67.     while(cur > 1) {
  68.         ans -= unite(ind, ind - len[cur] + 1);
  69.         cur = nxt[cur];
  70.     }
  71. }
  72.  
  73. int main() {
  74.     ios_base::sync_with_stdio(false);
  75.     cin.tie(nullptr);
  76.     init();
  77.     string str;
  78.     cin >> str;
  79.     ans = str.size();
  80.     for(int i = 0; i < (int)str.size(); i++) {
  81.         add_letter(str[i], i);
  82.     }
  83.     cout << ans << "\n";
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement