2017女生赛 1003 Coprime Sequence【前缀后缀维护】

版权声明:噗噗个噗~~~ https://blog.csdn.net/Puyar_/article/details/71328838

Coprime Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 0    Accepted Submission(s): 0


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(1T10), denoting the number of test cases.
In each test case, there is an integer n(3n100000) in the first line, denoting the number of integers in the sequence.
Then the following line consists of n integers a1,a2,...,an(1ai109), 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
 

比赛时数据水,被我水过去啦==(当时思路是:随便找三个数,然后去枚举他们的约数)

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
using namespace std;
#define ll long long
#define ms(a,b)  memset(a,b,sizeof(a))
const int M=1e6+10;
const int inf=0x3f3f3f3f;
int i,j,k,n,m;
ll a[M];
ll g1[M];
ll g2[M];

ll gcd(ll a,ll b)
{
    return b==0?a:gcd(b,a%b);
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--){
        ll kk;
        scanf("%d",&n);
       for(int i=1;i<=n;i++){
          scanf("%lld",&a[i]);
           if(i==1)g1[1]=a[1],kk=a[1];
           else {g1[i]=gcd(kk,a[i]);kk=g1[i];}
        }
        for(int i=n;i>=1;i--){
           if(i==n)g2[n]=a[n],kk=a[n];
           else {g2[i]=gcd(kk,a[i]);kk=g2[i];}
        }
       ll ans=1;
       for(int i=1;i<=n;i++){
            if(i==1)ans=max(ans,g2[i+1]);
            else if(i==n)ans=max(ans,g1[i-1]);
            else ans=max(ans,gcd(g1[i-1],g2[i+1]));
         }
        printf("%lld\n",ans);
    }
    return 0;
}




展开阅读全文

没有更多推荐了,返回首页