HDU - 6025辗转相除法+前缀后缀

 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.
 

Input
The first line of the input contains an integer  T(1T10), denoting the number of test cases.
In each test case, there is an integer  n(3n100000) in the first line, denoting the number of integers in the sequence.
Then the following line consists of  n integers  a1,a2,...,an(1ai109), 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
#include
#include
#include
#include
#define MAXX 100000
#include
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

你可能感兴趣的:(HDU,训练赛)