Salvens

G

Aug 7th, 2023
505
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3.  
  4. using namespace std;
  5.  
  6. #define int long long
  7.  
  8. const long long INF = 1e9 + 7;
  9. const int MAXN = 200 + 10;
  10. const int N = 1e5 + 10;
  11.  
  12. struct GCD_on_window {
  13.     stack<pair<int, int>> l, r;
  14.     int max_size;
  15.  
  16.     GCD_on_window(int k) {
  17.         max_size = k;
  18.     }
  19.  
  20.     void Clear() {
  21.         while (!l.empty()) {
  22.             if (r.empty()) {
  23.                 r.emplace(l.top().first, l.top().first);
  24.             } else {
  25.                 r.emplace(l.top().first, __gcd(l.top().first, r.top().second));
  26.             }
  27.             l.pop();
  28.         }
  29.     }
  30.  
  31.     void Delete() {
  32.         if (r.empty()) {
  33.             Clear();
  34.         }
  35.         r.pop();
  36.     }
  37.  
  38.     void Push(int x) {
  39.         int g = x;
  40.         if (r.empty()) {
  41.             Clear();
  42.         }
  43.         if (!l.empty()) {
  44.             g = __gcd(x, l.top().second);
  45.         }
  46.         if (l.size() + r.size() + 1 > max_size) {
  47.             Delete();
  48.         }
  49.         l.emplace(x, g);
  50.     }
  51.  
  52.     int GetGCD() {
  53.         int x = (l.empty()? -1: l.top().second);
  54.         int y = (r.empty()? -1: r.top().second);
  55.         if (x == -1) {
  56.             return y;
  57.         }
  58.         if (y == -1) {
  59.             return x;
  60.         }
  61.         return __gcd(x, y);
  62.     }
  63. };
  64.  
  65. signed main() {
  66.     ios_base::sync_with_stdio(false);
  67.     cin.tie(nullptr);
  68.     cout.tie(nullptr);
  69.  
  70.     int n;
  71.     cin >> n;
  72.     vector<int> a(n);
  73.     for (int i = 0; i < n; ++i) {
  74.         cin >> a[i];
  75.     }
  76.     GCD_on_window st(n);
  77.     int ans = INF;
  78.     int l = 0;
  79.     for (int r = 0; r < n; ++r) {
  80.         st.Push(a[r]);
  81.         while (st.GetGCD() == 1 && l <= r) {
  82.             ans = min(ans, r - l + 1);
  83.             st.Delete();
  84.             ++l;
  85.         }
  86.     }
  87.     cout << (ans == INF ? -1 : ans) << '\n';
  88. }
Advertisement
Add Comment
Please, Sign In to add comment