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; }
相关文章推荐
- HDU - 6025 Coprime Sequence(前缀,后缀,gcd)
- HDU 6025 Coprime Sequence(前缀后缀GCD问题)
- HDU 6025 Coprime Sequence 前缀gcd + 后缀gcd
- HDU 6025 Coprime Sequence
- HDU 6025 Coprime Sequence
- Coprime Sequence HDU - 6025
- Coprime Sequence HDU - 6025
- (HDU 6025 女生专场)Coprime Sequence 水题
- hdu 6025 Coprime Sequence (前后缀GCD)
- HDU 6025 Coprime Sequence (前后缀+GCD)
- ccpc 女生专场 C - Coprime Sequence HDU - 6025
- CSP认证训练题——Coprime Sequence HDU - 6025
- hdu 6025 Coprime Sequence
- HDU - 6025 Coprime Sequence(给出一行数,去掉其中一个数,求这行数的最大的最大公约数(gcd)))
- HDU-6025-coprime sequence
- HDU - 6025 Coprime Sequence
- HDU 6025 Coprime Sequence
- 【HDU】4135 Co-prime(容斥原理简单应用 质因子的分解)
- HDU6025 Coprime Sequence【前缀GCD+后缀GCD】
- HDU6025 Coprime Sequence —— 前缀和 & 后缀和