题解:P5502 [JSOI2015] 最大公约数

· · 题解

题意:

求 W(L,R) = (R-L+1) × \gcd (A_l,\dots,A_r) 的最大值。

思路

子序列问题通常可以使用分治算法来解决,我们考虑怎样算左右区间中间的值,发现 \gcd 的个数不超过 \log V 于是可以暴力找出所有的的 \gcd 处在的离中间最远的位置,暴力计算每一对即可。

#include<bits/stdc++.h>
#define int long long
#define mk make_pair
#define pii pair<int,int>
#define fi first
#define se second
using namespace std;
const int MAXN=2e5+10;
int n,a[MAXN],res,c[MAXN];
void solve(int l,int r){
    if(l==r) return res=max(res,a[l]),void();
    int mid=l+r>>1;
    solve(l,mid);solve(mid+1,r);
    int now=a[mid+1];unordered_map<int,int>mpr,mpl;mpr[now]=mid+1;
    for(int i=mid+2;i<=r;i++) {
        now=__gcd(now,a[i]),mpr[now]=i;
    }now=a[mid];mpl[now]=mid;
    for(int i=mid-1;i>=l;i--) now=__gcd(now,a[i]),mpl[now]=i;
    for(auto x:mpl){
        for(auto y:mpr){
            res=max(res,__gcd(x.fi,y.fi)*(y.se-x.se+1));
        }
    }
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL),cout.tie(NULL);
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    solve(1,n);cout<<res;
    return 0;
}