Coprime Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 424 Accepted Submission(s): 230
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(1≤T≤10), denoting the number of test cases.
In each test case, there is an integer n(3≤n≤100000) in the first line, denoting the number of integers in the sequence.
Then the following line consists of n integers a1,a2,…,an(1≤ai≤109), 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
3
3
1 1 1
5
2 2 2 3 2
4
1 2 4 8
Sample Output
1
2
2
题意:给你n个数,让你删除其中任意一个数,使剩下的数的gcd最大。
解题思路:因为只删除其中一个,所以我们很容易想到了枚举每一个要删除数字求剩下的数字的gcd就行,最后取最大值,问题就是怎样求剩下的数字的gcd,我在这里用的是rmq,然后还有一种更简单的做法,就是记录前缀gcd和后缀gcd,每次枚举时直接用就行。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
typedef long long ll;
int n;
ll a[maxn];
ll dp[maxn][25];
int Log[maxn];
ll gcd(ll x,ll y)
{
return x == 0?y:gcd(y%x,x);
}
void initRmq()
{
Log[0] = -1;
for(int i = 1; i <= n; i++)
{
Log[i] = ((i&(i - 1)) == 0)?Log[i - 1] + 1:Log[i - 1];
dp[i][0] = a[i];
}
for(int j = 1; j < 25; j++)
{
for(int i = 1; i <= n&&(i + (1<<j) - 1) <= n; i++)
{
dp[i][j] = gcd(dp[i][j - 1],dp[i + (1<<(j - 1))][j - 1]);
}
}
}
ll rmq(int l,int r)
{
int d = r - l + 1;
int j = Log[d];
return gcd(dp[l][j],dp[r - (1<<j) + 1][j]);
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i = 1; i <= n; i++)
{
scanf("%lld",&a[i]);
}
initRmq();
ll Max = 1;
ll g;
for(int i = 1; i <= n; i++)
{
if(i == 1) g = rmq(i + 1,n);
else if(i == n) g = rmq(1,n - 1);
else
{
int g1 = rmq(1,i - 1);
int g2 = rmq(i + 1,n);
g = gcd(g1,g2);
}
Max = max(Max,g);
}
printf("%lld\n",Max);
}
return 0;
}