首页 > 代码库 > HDU 6025 Coprime Sequence
HDU 6025 Coprime Sequence
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.
``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.
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
题意:
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。