HDU 6025 - Coprime Sequence ( 前缀gcd+后缀gcd )
题意
给出一个数组, 删一个数使得剩余数字构成的gcd最大
思路
借鉴前缀和思路
求出前缀gcd+后缀gcd, 通过这两个数组来求最大gcd即可
AC代码
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#define mst(a) memset(a, 0, sizeof(a))
using namespace std;
int gcd( int a, int b ){
return b == 0 ? a : gcd(b, a%b);
}
const int maxn = 1e5+5;
int pre[maxn], suf[maxn];
int a[maxn];
int main()
{
int T, n;
scanf("%d",&T);
while(T--){
mst(pre);
mst(suf);
mst(a);
scanf("%d",&n);
for( int i = 1; i <= n; i++ )
scanf("%d",&a[i]);
pre[1] = a[1];
for( int i = 2; i <= n; i++ )
pre[i] = gcd(a[i], pre[i-1]);
suf[n] = a[n];
for( int i = n-1; i >= 1; i-- )
suf[i] = gcd(a[i], suf[i+1]);
int gg = max(pre[n-1], suf[2]);
for( int i = 2; i <= n-1; i++ )
gg = max(gg, gcd(pre[i-1], suf[i+1]));
printf("%d\n",gg);
}
return 0;
}