HDU - 6025 Coprime Sequence(gcd+前綴後綴)
阿新 • • 發佈:2018-08-24
scan inpu define npos follow return ans lin print 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\n",maxx); } return 0; }
HDU - 6025 Coprime Sequence(gcd+前綴後綴)