UVA-1642 Magical GCD (GCD Properties)

The meaning of the question: a sequence of length n, select a continuous subsequence, so that the common divisor * length of the subsequence is the largest, find the maximum value, n<=1e5.

Idea: For a number A, the most different gcd values ​​are at most logA

Each time you take a value to the right, you can get the different gcd value of the current position as long as you take the gcd value from the different gcd value of the previous position.

Similar use of this nature is HDU-5869, 2016icpc Dalian Network Competition


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
map<ll,ll> mp;
ll n,x,ans;

ll gcd(ll x, ll y){
    return y==0?x:gcd(y,x%y);
}

int main(){
    int T; scanf("%d",&T);
    while(T--){
        scanf("%lld",&n);
        mp.clear();
        years=0;
        for (int i=1; i<=n; i++){//enumerate the right endpoint
            scanf("%lld",&x);
            if (!mp.count(x)) mp[x]=i;
            for (map<ll,ll>::iterator it=mp.begin(); it!=mp.end(); ){
                ll tmp=gcd(x,it->first);
                ans=max(ans,tmp*(i-it->second+1));
                if (!mp.count(tmp))
                    mp[tmp]=it->second;
                else
                    mp[tmp]=min(mp[tmp],it->second);
                //tmp cannot be greater than it->first, only tmp<=it->first
                if (tmp<it->first)
                    mp.erase(it++);
                else it++;
            }
        }
        printf("%lld\n",ans);
    }

    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324609605&siteId=291194637
gcd