UVA1642:Magical GCD

UVA1642:Magical GCD

Meaning of the questions:

Given a length \ (n-\ Leq. 5 ^ 10 \) , each number \ (a_i \ leq10 12 is ^ {} \) , looking for a continuous sequence such that the product of the length of the maximum subsequence convention.

\ (T \) set of data.

Ideas:

Interval greatest common divisor template title.

Enumeration \ ((i, j) \ ) violence, then the time complexity is \ (O (the n-^ 2logn) \) , will certainly timeout.

Given sequence \ (A \) , consecutive sub-segments \ (GCD \) have \ (log (max \ {a_i \}) \) possible.

\(gcd(1,..,i)=gcd(gcd(1,..,i-1),a(i))\)

So every time a fixed point right, to the left to find a different \ (gcd \) values.

#include<bits/stdc++.h>
#define PLI pair<long long, int>
using namespace std;
typedef long long ll;
const int maxn = 1e5+10;
ll a[maxn];
int n;

ll gcd(ll a, ll b)
{
    if(b == 0) return a;
    return gcd(b, a%b);
}

//fir->gcd sec->右端点索引
vector<PLI> g[maxn];

void solve()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
    {
        scanf("%lld", &a[i]);
        g[i].clear();
    }
    for(int i = 1; i <= n; i++)
    {
        ll x = a[i], y = i;
        g[i].push_back({x,y});
        for(int j = 0; j < g[i-1].size(); j++)
        {
            PLI p = g[i-1][j];
            ll t = gcd(x, p.first);
            if(t != x)
            {
                x = t; y = p.second;
                g[i].push_back({x, y});
            }
        }
    }

    ll ans = 0;
    for(int i = 1; i <= n; i++)
    {
        PLI p1, p2;
        for(int j = 0; j < g[i].size()-1; j++)
        {
            p1 = g[i][j];
            p2 = g[i][j+1];
            ans = max(ans, p1.first*(i-p2.second));
        }
        p1 = g[i][g[i].size()-1];
        ans = max(ans, (ll)(i)*p1.first);
    }

    cout << ans << endl;
}

int main()
{
    int T; scanf("%d", &T);
    while(T--) solve();
    return 0;
}

Guess you like

Origin www.cnblogs.com/zxytxdy/p/12306167.html
gcd