Coprime Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 1527 Accepted Submission(s): 733
http://acm.hdu.edu.cn/showproblem.php?pid=6025
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.
``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.
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
331 1 152 2 2 3 241 2 4 8
Sample Output
122
本题题意就是一个序列,去掉一个其中一个数,使得GCD尽可能大开始的大,用两层for循环,第一层a[i]对应去掉a[i]时的序列
第二层循环再次暴力序列用辗转相除法找到GCD....后来就T掉了。一看范围n^2复杂度,大概是1e10肯定T。。。然后第二层从两边往中间暴力,复杂度改成1/2*n^2还是T。。。
最后用前几天学的前缀和,pre[i]表示a[i]前的GCD,backk[i]表示a[i]后的GCD,这样一次线性N/2的复杂度就算出前缀与后缀,最后1->N暴力,再次取GCD即可,用MAX保存更新,最后输出即可
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#define MAXX 100000
#include<map>
using namespace std;
int gcd(int a,int b){
return b==0?a:gcd(b,a%b);
}
int main(){
int n,maxx,gc,t,gc1,gc2,ans;
int pre[MAXX+5];
int backk[MAXX+5];
int a[MAXX+5];
scanf("%d",&t);
while (t--){
maxx=0;
gc=0;
scanf("%d",&n);
for (int i=0;i<n;i++){
scanf("%d",&a[i]);
}
pre[0]=a[0];
backk[n-1]=a[n-1];
for (int i=1;i<n;i++){
pre[i]=gcd(pre[i-1],a[i]);
backk[n-i-1]=gcd(backk[n-i],a[n-i-1]);
}
int ans=max(pre[n-2],backk[1]);
for(int i=1;i<n-1;i++){
ans=max(gcd(pre[i-1],backk[i+1]),ans);
}
printf("%d\n",ans);
}
return 0;
}