HDU 6025 Coprime Sequence【前缀GCD+后缀GCD】

Do you know what is called ``Coprime Sequence''? That is a sequence consists of nnpositive 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)T(1≤T≤10), denoting the number of test cases. 
In each test case, there is an integer n(3≤n≤100000)n(3≤n≤100000) in the first line, denoting the number of integers in the sequence. 
Then the following line consists of nn integers a1,a2,...,an(1≤ai≤109)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

PS:相信,题意大家都能读懂吧,就是去掉一个数是剩下的GCD最大。这里使用两个数组,一个前缀GCD数组和一个后缀GCD数组。细节看代码。

#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include<cmath>
#include<stack>
#include<string>
const int maxn=1e6+10;
const int mod=1e9+7;
const int inf=1e8;
#define me(a,b) memset(a,b,sizeof(a))
typedef long long ll;
using namespace std;
int gcd(int a,int b)
{
    return b==0?a:gcd(b,a%b);
}
int a[maxn],l[maxn],r[maxn];
int main()
{
   int t;cin>>t;
   while(t--)
   {
       int n;scanf("%d",&n);
       for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        l[1]=a[1],r[n]=a[n];
        for(int i=2;i<=n;i++)
            l[i]=gcd(l[i-1],a[i]);///保存前i项的GCD
        for(int i=n-1;i>0;i--)
            r[i]=gcd(r[i+1],a[i]);///保存后i项的GCD
        int ans=max(l[n-1],r[2]);///因为数组是1到n,并且下面有i-1和i+1所以不能是max(l[n],r[1]);
        for(int i=2;i<n;i++)
            ans=max(ans,gcd(l[i-1],r[i+1]));///gcd(l[i-1],r[i+1])就表示除开第i项后数列的GCD、
        cout<<ans<<endl;
   }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41292370/article/details/82497185