1. 程式人生 > >HDU 6025 Coprime Sequence

HDU 6025 Coprime Sequence

iso build eno one ase fine amp comm ``

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.


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 a技術分享1技術分享,a技術分享2技術分享,...,a技術分享n技術分享(1a技術分享i技術分享10技術分享9技術分享)技術分享, 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

題意:

T組樣例,給出 N 個數,求去掉一個數後,數列的最大 GCD。

思路:

維護前綴 GCD 和 後綴GCD 即可。

代碼裏使用了線段樹,其實完全沒有必要。

#include <bits/stdc++.h>  
  
using
namespace 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