HDU 6025 Coprime Sequence
阿新 • • 發佈:2017-05-08
iso build eno one ase fine amp comm `` Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
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(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.
Output
For 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
Coprime Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 44 Accepted Submission(s): 34
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.
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.
題意:
T組樣例,給出 N 個數,求去掉一個數後,數列的最大 GCD。
思路:
維護前綴 GCD 和 後綴GCD 即可。
代碼裏使用了線段樹,其實完全沒有必要。
#include <bits/stdc++.h> usingnamespace std; #define ls l,mid,rt*2 #define rs mid+1,r,rt*2+1 #define sf l,r,rt #define mi (l+r)/2; const int MAXN=1e6+100; int tree[4*MAXN],st,en; int gcd(int x,int y){return y==0?x:gcd(y,x%y);} void push_up(int l,int r,int rt){ tree[rt]=gcd(tree[rt*2],tree[rt*2+1]); } void build(int l,int r,int rt){ if(l==r){scanf("%d",&tree[rt]);return ;} int mid=mi; build(ls);build(rs); push_up(sf); return ; } int query(int l,int r,int rt){ if(r<st||l>en) return 0; if(st<=l&&r<=en) return tree[rt]; int mid=mi; int ans=query(ls); if(ans==0) ans=query(rs); else ans=gcd(ans,query(rs)); return ans; } int main() { int T,n; scanf("%d",&T); while(T--){ scanf("%d",&n); build(1,n,1); int ans=-1; for(int i=2;i<n;i++){ st=1;en=i-1; int temp=query(1,n,1); st=i+1;en=n; temp=gcd(temp,query(1,n,1)); ans=max(ans,temp); } st=2;en=n; ans=max(query(1,n,1),ans); st=1;en=n-1; ans=max(query(1,n,1),ans); printf("%d\n",ans); } }
轉自:http://blog.csdn.net/dt2131/article/details/71424843#
HDU 6025 Coprime Sequence