HDU - 6025辗转相除法+前缀后缀

 Coprime Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 1527    Accepted Submission(s): 733
http://acm.hdu.edu.cn/showproblem.php?pid=6025

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
 
 
331 1 152 2 2 3 241 2 4 8
 

Sample Output
 
 
122

    

本题题意就是一个序列,去掉一个其中一个数,使得GCD尽可能大开始的大,用两层for循环,第一层a[i]对应去掉a[i]时的序列

第二层循环再次暴力序列用辗转相除法找到GCD....后来就T掉了。一看范围n^2复杂度,大概是1e10肯定T。。。然后第二层从两边往中间暴力,复杂度改成1/2*n^2还是T。。。

最后用前几天学的前缀和,pre[i]表示a[i]前的GCD,backk[i]表示a[i]后的GCD,这样一次线性N/2的复杂度就算出前缀与后缀,最后1->N暴力,再次取GCD即可,用MAX保存更新,最后输出即可

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#define MAXX 100000
#include<map>
using namespace std;
int gcd(int a,int b){
  return b==0?a:gcd(b,a%b);
}
  int main(){
    int n,maxx,gc,t,gc1,gc2,ans;
    int pre[MAXX+5];
    int backk[MAXX+5];
    int a[MAXX+5];
    scanf("%d",&t);
    while (t--){
       maxx=0;
       gc=0;
       scanf("%d",&n);
       for (int i=0;i<n;i++){
        scanf("%d",&a[i]);
       }
       pre[0]=a[0];
       backk[n-1]=a[n-1];
       for (int i=1;i<n;i++){
             pre[i]=gcd(pre[i-1],a[i]);
             backk[n-i-1]=gcd(backk[n-i],a[n-i-1]);
       }
       int ans=max(pre[n-2],backk[1]);
       for(int i=1;i<n-1;i++){
          ans=max(gcd(pre[i-1],backk[i+1]),ans);
       }
       printf("%d\n",ans);
    }
    return 0;
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值