1642 Magical GCD
and the greatest common divisor of all its elements.
Given a sequence (a1, . . . , an), find the largest possible Magical GCD of its connected subsequence.
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
15
30 60 20 20 20
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;
}