[JSOI2015]最大公约数

题目

一个非常众所周知的结论,一个序列的前缀\(\gcd\)只会有\(\log\)种取值

于是考虑一下一些暴力的东西,我们枚举每个点作为左端点,二分出前缀\(\gcd\)变化的位置,复杂度大概是\(\operatorname{O(nlog^3n)}\),好像非常垃圾的样子

我们考虑直接从后往前枚举左端点,每次往前加入一个数,和之前的前缀\(\gcd\)再取一个\(\gcd\)就好了,同时合并掉相同的一段

复杂度是\(\operatorname{O(nlog^2n)}\),还是挺丢人的

代码

#include<bits/stdc++.h>
#define re register
#define LL long long
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
inline LL read() {
    char c=getchar();LL x=0;while(c<'0'||c>'9') c=getchar();
    while(c>='0'&&c<='9') x=(x<<3ll)+(x<<1ll)+c-48,c=getchar();return x;
}
const int maxn=1e5+5;
LL gcd(LL a,LL b) {return !b?a:gcd(b,a%b);}
LL a[maxn];
int n;LL ans;
LL b[maxn],c[maxn];int p[maxn],top,t[maxn];
int main() {
    n=read();
    for(re int i=1;i<=n;i++) a[i]=read();
    ans=a[n];b[++top]=ans;p[1]=n;
    for(re int i=n-1;i;--i) {
        for(re int j=top;j;--j)
            b[j]=gcd(b[j],a[i]);
        b[++top]=a[i];p[top]=i;
        int tot=0;
        for(re int j=top-1;j>=0;--j) {
            if(b[j]==b[j+1]) continue;
            c[++tot]=b[j+1],t[tot]=p[j+1];
        }
        top=tot;
        for(re int j=top;j;--j) 
            b[j]=c[top-j+1],p[j]=t[top-j+1],ans=max(ans,1ll*b[j]*(p[j]-i+1));
    }
    printf("%lld\n",ans);
    return 0;
}

转载于:https://www.cnblogs.com/asuldb/p/11348104.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值