您的位置:首页 > 产品设计 > UI/UE

L - Coprime Sequence HDU - 6025(前缀和的应用)

2020-07-16 06:07 701 查看

Do you know what is called

Coprime Sequence''? That is a sequence consists of n positive integers, and the GCD (Greatest Common Divisor) of them is equal to 1.
Coprime Sequence’’ is easy to find because of its restriction. But we can try to maximize the GCD of these integers by removing exactly one integer. Now given a sequence, please maximize the GCD of its elements.

Input
The first line of the input contains an integer T(1≤T≤10), denoting the number of test cases.
In each test case, there is an integer n(3≤n≤100000) in the first line, denoting the number of integers in the sequence.
Then the following line consists of n integers a1,a2,…,an(1≤ai≤109), denoting the elements in the sequence.

Output
For each test case, print a single line containing a single integer, denoting the maximum GCD.

题意:去掉一个数,使得剩下的所有数的最大公约数最大!
这道题看上去是利用两两之间进行gcd,实则会达到O(n^2)是不可取的
然后通过前缀和优化,求出左右gcd(l[i - 1], r[i + 1])即可,这也就把a[ i ]给剔除了,然后遍历一遍就是O(n)的

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;

const int N = 100010;
int l[N], r[N], p[N];

int gcd(int a, int b)
{
return b ? gcd(b, a % b) : a;
}

int main(void)
{
int T, n, g;
scanf("%d", &T);
while(T -- )
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", &p[i]);

for(int i = 0; i < n; i ++ )
{
if(i == 0) g = p[i];
else g = gcd(p[i], l[i - 1]);
l[i] = g;
}

for(int i = n - 1; i >= 0; i -- )
{
if(i == n - 1) g = p[n - 1];
else g = gcd(p[i], r[i + 1]);
r[i] = g;
}
int maxg = -1;
for(int i = 0; i < n; i ++ )
{
if(i == 0) g = r[1];
else if(i == n - 1) g = l[n-2];
else
{
//去掉i这个数找其他的最大公约数
g = gcd(l[i - 1], r[i + 1]);
}
maxg = max(maxg, g);
}
cout << maxg << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: