码迷,mamicode.com
首页 > 其他好文 > 详细

HDU - 6025 Coprime Sequence(gcd+前缀后缀)

时间:2018-08-24 21:19:23      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:rest   comm   cas   each   using   ssis   后缀   data-   ini   

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.

InputThe first line of the input contains an integer T(1T10)T(1≤T≤10), denoting the number of test cases. 
In each test case, there is an integer n(3n100000)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(1ai109)a1,a2,...,an(1≤ai≤109), denoting the elements in the sequence.
OutputFor 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最大。
典型的预处理。将每个值的前缀和后缀求出来,扫一遍每个值,ans=max(ans,gcd(前缀,后缀))

#include <iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<stdlib.h>
#include<math.h>
#include<set>
#include<map>
#include<algorithm>
#define MAX 100005
#define INF 0x3f3f3f3f
using namespace std;

int a[MAX];
int pre[MAX],sub[MAX];
int gcd(int x,int y){
    if(y) return gcd(y,x%y);
    return x;
}
int main()  
{  
    int t,f,h,n,m,k,i,j;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        scanf("%d",&a[1]);
        pre[1]=a[1];
        for(i=2;i<=n;i++){
            scanf("%d",&a[i]);
            pre[i]=gcd(pre[i-1],a[i]);
        }
        sub[n]=a[n];
        for(i=n-1;i>=1;i--){
            sub[i]=gcd(sub[i+1],a[i]);
        }
        int maxx=(pre[n-1]>sub[2]?pre[n-1]:sub[2]);
        for(i=2;i<n;i++){
            if(gcd(pre[i-1],sub[i+1])>maxx) maxx=gcd(pre[i-1],sub[i+1]);
        }
        printf("%d\n",maxx);
    }
    return 0;  
}  

 

 

HDU - 6025 Coprime Sequence(gcd+前缀后缀)

标签:rest   comm   cas   each   using   ssis   后缀   data-   ini   

原文地址:https://www.cnblogs.com/yzm10/p/9531953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!