Advertisement
MinhNGUYEN2k4

DIVSEQ || Z function

Sep 8th, 2020
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.77 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. const int N = 3 * 100005;
  5.  
  6. int n,z[N],a[N];
  7. priority_queue<int, vector<int>, greater<int>> qu;
  8.  
  9. int main()
  10. {
  11.     ios_base::sync_with_stdio(false);
  12.     cin.tie(0);cout.tie(0);
  13.     freopen("divseq.inp","r",stdin);
  14.     cin >> n;
  15.     for(int i=1; i<=n; ++i) {
  16.         cin >> a[i];
  17.     }
  18.     z[1]=0;
  19.     for(int k=2, r=1, l=1; k<=n; ++k) {
  20.         int x=0;
  21.         int kk = k-l+1;
  22.         if (k <= r) x = min(z[kk],r-k+1);
  23.         while (a[x+1] == a[x+k] && k + x <= n) ++x;
  24.         z[k] = x;
  25.         if (r < k + x - 1) {
  26.             l = k;
  27.             r = k + x - 1;
  28.         }
  29.     }
  30.     for(int i=1; i<=n; ++i) {
  31.         if (z[i+1] + i == n) qu.push(i);
  32.         cout << z[i] << " ";
  33.     }
  34.     cout << qu.top();
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement