P11753 [COCI 2024/2025 #5] 塔楼 / Tornjevi 题解

· · 题解

单调栈简单线性做法。

题意

给定序列 h_i,对于每个 i,求出包含 i 且 \gcd\limits_{j=l}^{r}h_j=h_i 的最大区间。

思路

### 代码 ```cpp #include <bits/stdc++.h> using namespace std; constexpr int N=1e6+6; int n,a[N],l[N],r[N],st[N],top; signed main(){ clock_t _st=clock(); cin>>n; for(int i=1;i<=n;i++)cin>>a[i]; st[top=1]=l[1]=1; for(int i=2;i<=n;i++){ while(top&&!(a[st[top]]%a[i]))--top; l[i]=st[top]+1,st[++top]=i; } st[0]=n+1,st[top=1]=r[n]=n; for(int i=n-1;i>=1;i--){ while(top&&!(a[st[top]]%a[i]))--top; r[i]=st[top]-1,st[++top]=i; } for(int i=1;i<=n;i++)cout<<r[i]-l[i]+1<<' ';cout<<'\n'; clock_t _ed=clock(); cerr<<(_ed-_st)*1.0/CLOCKS_PER_SEC<<'\n'; return 0; } ```