首页 > 代码库 > BZOJ 4052 Magical GCD

BZOJ 4052 Magical GCD

前缀有log个gcd,用代码中的方法来将nlog^3n优化为nlog^2n。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 100050
using namespace std;
long long t,n,a[maxn],tot[maxn],f[maxn][50],g[maxn][50],ans=0;
long long gcd(long long a,long long b)
{
    if (b==0) return a;
    return gcd(b,a%b);
}
void work()
{
    memset(tot,0,sizeof(tot));
    scanf("%lld",&n);
    for (long long i=1;i<=n;i++) scanf("%lld",&a[i]);
    for (long long i=1;i<=n;i++)
    {
        for (long long j=1;j<=tot[i-1];j++)
        {
            long long now=gcd(a[i],f[i-1][j]);
            if (now!=f[i][tot[i]])
            {
                f[i][++tot[i]]=now;
                g[i][tot[i]]=g[i-1][j];
            }
        }
        if (a[i]!=f[i][tot[i]])
        {
            f[i][++tot[i]]=a[i];
            g[i][tot[i]]=i;
        }
    }
    ans=0;
    for (long long i=1;i<=n;i++)
        for (long long j=1;j<=tot[i];j++)
            ans=max(ans,f[i][j]*(i-g[i][j]+1));
    printf("%lld\n",ans);
}
int main()
{
    scanf("%lld",&t);
    for (long long i=1;i<=t;i++)
        work();
    return 0;
}

 

BZOJ 4052 Magical GCD