跳到正文

题解

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

Redolent约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年7月8日
收录
2026年8月6日
更新
2026年11月14日
篇幅
约 2 分钟
获赞
1
题目
P11753

版本

  1. v1当前

单调栈简单线性做法。

题意

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

思路

gcd⁡\gcd 的本质是对质因数取 min⁡\min。因此可以转化为查询对于每个质因数,次数最小值等于 kik_i 的最大区间,这样的结构可以使用单调栈。维护一个单调栈,满足栈内上一个数不整除下一个数,相当于上一个存在质因数的次数大于这个数的位置。跑两遍单调栈求出每个位置对应的左右端点即可。

代码

C++
#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;
}
原文