[HDU](6025) Coprime Sequence ---- 前缀GCD+后缀GCD

Problem Description

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.

Sample Input

3
3
1 1 1
5
2 2 2 3 2
4
1 2 4 8

Sample Output

1
2
2

题意:
给你一个互质序列,即gcd(a1,a2,a3,…,an) = 1, 让你删去一个元素,使得这个序列的GCD最大化。
思路: 1e5的范围,暴力枚举是肯定过不了的,那么我们可以利用前缀和后缀处理优化。
我们先求出来前缀GCD 保存在 l数组 中,然后求出来后缀GCD 保存在 r 数组中,这些操作都是
O(n*logn) ,然后我们在遍历一遍,求GCD(x1,x2),其中x1是l数组的元素,x2是r数组中的元素, 保证 x2 - x1 = 2, 即 去除x1和x2中间的元素xi 后,GCD(x1,x2)就是求剩下的元素求最大公约数。
AC代码:

#include<bits/stdc++.h>
using namespace std;
#define pb         push_back
#define sz(x)      int(x.size()-1)
#define lop(i,s,e) for (int i=s;i<=e;i++)
#define lep(i,s,e) for (int i=e;i>=s;i--)
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9+7;
const int maxn = 1e5+5;
int a[maxn],l[maxn],r[maxn],ans[maxn];
int t,n;
int gcd(int a,int b)
{
    if(!b) return a;
    else return gcd(b,a%b);
}
void solve()
{
    l[1] = a[1],r[n] = a[n];
    lop(i,2,n) l[i] = gcd(l[i-1],a[i]);
    lep(i,1,n-1) r[i] = gcd(r[i+1],a[i]);
    int res = max(l[n-1],r[2]);//1和n里面挑一个最大的
    lop(i,2,n) res = max(res,gcd(l[i-1],r[i+1])); //gcd(x1,x2)表示除了i之外的所有数的最大公约数
    cout<<res<<endl;
}
int main()
{
    #ifdef LOCAL
    freopen("in.txt","r",stdin);
    #endif // LOCAL
    ios_base::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin>>t;
    while(t--)
    {
        cin>>n;
        lop(i,1,n) cin>>a[i];
        solve();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37624640/article/details/80159095