[UVa 1642]Magical GCD STL map遍历

1642 Magical GCD


The Magical GCD of a nonempty sequence of positive integers is defined as the product of its length
and the greatest common divisor of all its elements.

Given a sequence (a1, . . . , an), find the largest possible Magical GCD of its connected subsequence.


Input
The first line of input contains the number of test cases T. The descriptions of the test cases follow:
The description of each test case starts with a line containing a single integer n, 1 ≤ n ≤ 100000.
The next line contains the sequence a1, a2, . . . , an, 1 ≤ ai ≤ 1012
.
Output
For each test case output one line containing a single integer: the largest Magical GCD of a connected

subsequence of the input sequence.


Sample Input

1
5

30 60 20 20 20


Sample Output

80


题目大意

给定一个数列,求一个子列,该子列的最大公约数乘上子列长度的值最大,输出最大值。

解题思路

随着子列的增长,gcd在不断减小,于是我么对于当前值k,维护[i,k-1]的gcd 并与a[k]求gcd,若没有减小则新的gcd对应的区间便为[i,k];否则寻找gcd出现的第一个位置l,新的对应的区间位置即为[l,k]

直接用遍历map实现即可。


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <ctime>
#include <cctype>
#include <cmath>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <set>

#define sqr(x) ((x)*(x))
#define LL long long 
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define eps 1e-10
#define mod 100000007ll
using namespace std;
LL a[100005];
map<LL,LL>v;
map<LL,LL>::iterator it,itt;
int main()
{
    int T,n;
    scanf("%d",&T);

    while (T--)
    {
        LL ans=0;
        scanf("%d",&n);
        // n= 100000;
        v.clear();
        for (int i=1;i<=n;i++)
        {
            scanf("%lld",&a[i]);
            // a[i]=1000000000000;
            ans=max(ans,a[i]);
            for (it=v.begin();it!=v.end();it++)
            {
                if(__gcd(it->first,a[i])!=it->first)
                    {
                        if (v[__gcd(it->first,a[i])]==0)
                            v[__gcd(it->first,a[i])]=it->second;
                        itt=it++;
                        v.erase(itt,it);
                        it--;
                    }
            }
            if (v[a[i]]==0)v[a[i]]=i;
            for (it=v.begin();it!=v.end();it++)
            {
                ans=max(ans,(it->first)*(i-it->second+1));
                // printf("%lld %lld|",it->first,it->second);
            }
            // puts("");
        }
        printf("%lld\n",ans);
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值