HDU - 6025 Coprime Sequence(gcd+前缀后缀)
Posted yzm10
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU - 6025 Coprime Sequence(gcd+前缀后缀)相关的知识,希望对你有一定的参考价值。
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.
``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.
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 8
Sample Output
1 2 2
去掉一个值,使得剩下的值gcd最大。
典型的预处理。将每个值的前缀和后缀求出来,扫一遍每个值,ans=max(ans,gcd(前缀,后缀))
#include <iostream> #include<stdio.h> #include<string.h> #include<string> #include<stdlib.h> #include<math.h> #include<set> #include<map> #include<algorithm> #define MAX 100005 #define INF 0x3f3f3f3f using namespace std; int a[MAX]; int pre[MAX],sub[MAX]; int gcd(int x,int y){ if(y) return gcd(y,x%y); return x; } int main() { int t,f,h,n,m,k,i,j; scanf("%d",&t); while(t--){ scanf("%d",&n); scanf("%d",&a[1]); pre[1]=a[1]; for(i=2;i<=n;i++){ scanf("%d",&a[i]); pre[i]=gcd(pre[i-1],a[i]); } sub[n]=a[n]; for(i=n-1;i>=1;i--){ sub[i]=gcd(sub[i+1],a[i]); } int maxx=(pre[n-1]>sub[2]?pre[n-1]:sub[2]); for(i=2;i<n;i++){ if(gcd(pre[i-1],sub[i+1])>maxx) maxx=gcd(pre[i-1],sub[i+1]); } printf("%d ",maxx); } return 0; }
以上是关于HDU - 6025 Coprime Sequence(gcd+前缀后缀)的主要内容,如果未能解决你的问题,请参考以下文章
hdu 6025 Coprime Sequence (前后缀GCD)