1. 程式人生 > >[HDU](6025) Coprime Sequence ---- 字首GCD+字尾GCD

[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;
}