GCD on Blackboard(前缀和+后缀和+思维)

GCD on Blackboard(前缀和+后缀和+思维)

题目描述
There are N integers, A1,A2,…,AN, written on the blackboard.
You will choose one of them and replace it with an integer of your choice between 1 and 109 (inclusive), possibly the same as the integer originally written.

Find the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Constraints
·All values in input are integers.
·2≤N≤105
·1≤Ai≤109

输入
Input is given from Standard Input in the following format:

N
A1 A2 … AN

输出
Print the maximum possible greatest common divisor of the N integers on the blackboard after your move.
样例输入 Copy
3
7 6 8

 

 

样例输出 Copy
2

 

提示
If we replace 7 with 4, the greatest common divisor of the three integers on the blackboard will be
2, which is the maximum possible value.

 

思路:求前缀及后缀,再求gcd,O(n)

#pragma GCC optimize(3 , "Ofast" , "inline")
 
#include <bits/stdc++.h>
 
#define rep(i , a , b) for(register int i=(a);i<=(b);i++)
#define rop(i , a , b) for(register ll i=(a);i<(b);i++)
#define per(i , a , b) for(register ll i=(a);i>=(b);i--)
#define por(i , a , b) for(register ll i=(a);i>(b);i--)
 
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int , int > pi;
template<class T>
inline void read (T &x) {
    x = 0;
    int sign = 1;
    char c = getchar ();
    while (c < '0' || c > '9') {
        if ( c == '-' ) sign = - 1;
        c = getchar ();
    }
    while (c >= '0' && c <= '9') {
        x = x * 10 + c - '0';
        c = getchar ();
    }
    x = x * sign;
}
const int maxn = 1e5+10;
const int inf = int (1e9);
const ll INF = ll(1e18);
const double PI = acos (-1);
const int mod = 1e9+7;
const double eps = 1e-8;
int a[maxn];
int b[maxn];
int c[maxn];
 
int main(){
    int n;
    read (n);
    rep (i,1,n) {
        read (a[i]);
    }
    b[1]=a[1];
    rep (i,2,n) {
        b[i]=__gcd (b[i-1],a[i]);
    }
    c[n]=a[n];
    per (i,n-1,1) {
        c[i]=__gcd (c[i+1],a[i]);
    }
    int ans = 0;
    rep (i,1,n) {
        ans=max (ans,__gcd (b[i-1],c[i+1]));
    }
    cout<<ans<<endl;
    return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值