C - Coprime Sequence
Do you know what is called ``Coprime Sequence''? That is a sequence consists of
nnpositive 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.
InputThe first line of the input contains an integer
T(1≤T≤10)T(1≤T≤10), denoting the number of test cases.
``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.
In each test case, there is an integer n(3≤n≤100000)n(3≤n≤100000) in the first line, denoting the number of integers in the sequence.
Then the following line consists of nn integers a1,a2,...,an(1≤ai≤109)a1,a2,...,an(1≤ai≤109), denoting the elements in the sequence.OutputFor 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 8Sample Output
1 2 2
题意:
n个数最大公约数为1。如果删掉一个数,使剩下的数的最大公约数最大,求这个集合的最大公约数。
方法一:
思路:
设这个最大公约数为x。
n个数先排序 —> a1,a2,a3......an
那必须有n-1个数都能除以x,即n-1个数都>=x
所以x最大是a2(排第二的数,不一定是第二小的)
所以,x的取值 i=a2;i>=1;i-- ,依次用ai除,当有n-1个数都可以除时,这个i为x
代码:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int t;
cin>>t;
int n;
int a[100005];
while(t--)
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
sort(a,a+n);
int h=a[1];
int flag=0;
for(int j=h;j>=1;j--)
{
int sum=0;
for(int i=0;i<n;i++)
{
if(a[i]%j==0)
sum++;
if(sum>=n-1)
{
flag=1;
cout<<j<<endl;
break;
}
}
if(flag==1)
break;
}
}
return 0;
}
方法二:
思路:
题意:给你一个序列,任意去掉一个,问整个序列的最大公约数。
前缀和,后缀和思想
求前缀最大公约数,后缀最大公约数,然后找gcd(前缀gcd,后缀gcd)中最大的。
具体思想:开两个数组,第一个数组a保存前缀gcd,a[i]表示,从1到i的最大公约数。第二个数组b保存后缀gcd,b[i]表示,从n到i的最大公约数。
去掉第i个数的最大公约数为gcd(a[i-1],b[i+1]).over!
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll mod = 1e9 + 7;
const ll maxn = 100005;
int l[maxn],r[maxn],num[maxn];
int main(){
std::ios::sync_with_stdio(false);
int T;cin>>T;
while(T--){
int n;cin>>n;
for(int i=0;i<n;i++) cin>>num[i];
l[0] = num[0];
r[n-1] = num[n-1];
for(int i=1;i<n;i++)
l[i] = __gcd(l[i-1],num[i]);
for(int i=n-2;i>=0;i--)
r[i] = __gcd(r[i+1],num[i]);
int d = max(l[n-2],r[1]);
for(int i=1;i<n-1;i++){
d = max(d,__gcd(l[i-1],r[i+1]));
}
cout<<d<<endl;
}
return 0;
}