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.
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.
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;
}