hdu 6025 Coprime Sequence(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

Source
2017中国大学生程序设计竞赛 - 女生专场
思路:枚举的话会超时,转换一下思维,就一下前缀gcd和后缀gcd就一目了然了。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+1;
ll a[maxn],pre[maxn],post[maxn];
ll gcd(ll a,ll b)
{
    return b==0?a:gcd(b,a%b);
}
int main()
{
    int T,n;
    scanf("%d",&T);
    while(T--)
    {
        ll ans=0;
        scanf("%d",&n);
        for(int i=1;i<=n;++i) scanf("%lld",&a[i]);
        pre[1]=a[1];
        for(int i=2;i<=n;++i)  pre[i]=gcd(pre[i-1],a[i]);
        post[n]=a[n];
        for(int i=n-1;i>=1;--i) post[i]=gcd(post[i+1],a[i]);
        ans=max(post[2],pre[n-1]);
        for(int i=2;i<n;++i)
        {
            ans=max(ans,gcd(pre[i-1],post[i+1]));
        }
        printf("%lld\n",ans);
    }
}
发布了171 篇原创文章 · 获赞 0 · 访问量 5804

猜你喜欢

转载自blog.csdn.net/qq_42479630/article/details/104590962