danielvitor23

Periods of Words

Sep 22nd, 2023 (edited)
1,106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. using i64 = long long;
  4. vector<int> getPi(const string &s) {
  5.   int n = (int)s.size();
  6.   vector<int> pi(n, 0);
  7.   for (int i = 1, j = 0; i < n; ++i) {
  8.     while (j > 0 and s[i] != s[j]) j = pi[j - 1];
  9.     if (s[i] == s[j]) ++j;
  10.     pi[i] = j;
  11.   }
  12.   return pi;
  13. }
  14. int main() {
  15.   cin.tie(0)->sync_with_stdio(0);
  16.   int n; cin >> n;
  17.   string s; cin >> s;
  18.   auto pi = getPi(s);
  19.   i64 ans = 0;
  20.   for (int i = n; i >= 2; --i) {
  21.     int d = i - pi[i-1];
  22.     if (i % d == 0) {
  23.       ans += (i - d);
  24.     } else {
  25.       ans += (d * (i / d));
  26.     }
  27.   }
  28.   cout << ans << '\n';
  29. }
  30. /*
  31.  
  32. b            ->          0
  33. ba           ->          0
  34. bab          -> ba       2
  35. baba         -> ba       2
  36. babab        -> baba     4
  37. bababa       -> baba     4
  38. bababab      -> bababa   6
  39. babababa     -> bababa   6
  40. total        =          24
  41.  
  42. */
Advertisement
Add Comment
Please, Sign In to add comment