244. Max Gcd
单点时限: 2.0 sec
内存限制: 512 MB
一个数组a ,现在你需要删除某一项使得它们的gcd 最大,求出这个最大值。
输入格式
第一行输入一个正整数n ,表示数组的大小,接下来一行n 个数,第i 个数为ai 。(2≤n≤105,1≤ai≤109)
输出格式
输出删除掉某个数以后的gcd 的最大值。
样例
Input
4
2 4 8 1
Output
2
Input
4
1 2 3 4
Output
1
提示
样例一:删除第四个元素后,2,4,8的最大公因子为2。
样例二:无论删除哪一个,最大公因子都为1。
用两个数组分别保存从左到右和从右到左的gcd值,然后用前驱数组[i-1]和后继数组[i+1]计算出的gcd就是除去i的最大gcd值了。
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define INF 0x3f3f3f3f
const int MAXN = (int)1e5 + 7;
int gcd(int a, int b)
{
return b ? gcd(b, a%b) : a;
}
int arr[MAXN];
int staa[MAXN];//前驱数组
int endd[MAXN];//后继数组
int main()
{
int n;
cin>>n;
for(int i = 0; i < n; i++)
{
cin>>arr[i];
}
staa[0] = arr[0];
endd[n-1] = arr[n-1];
for(int i = 1; i < n; i++)
{
staa[i] = gcd(staa[i-1], arr[i]);
}
for(int i = n-2; i >= 0; i--)
{
endd[i] = gcd(endd[i+1], arr[i]);
}
int maxx = -INF;
for(int i = 1; i <= n-2; i++)
{
maxx = max(maxx, gcd(staa[i-1], endd[i+1]));//去掉第i个的最大gcd
}
maxx = max(maxx, max(staa[n-2],endd[1]));//去掉第一个和去掉最后一个的特例
cout<<maxx<<endl;
return 0;
}
Coprime Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 4067 Accepted Submission(s): 1881
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
发现是一样的题,尴尬,暂且放这吧。再加一个t组数据就行了。
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define INF 0x3f3f3f3f
const int MAXN = (int)1e5 + 7;
int gcd(int a, int b)
{
return b ? gcd(b, a%b) : a;
}
int arr[MAXN];
int staa[MAXN];
int endd[MAXN];
int main()
{
int t, n;
cin>>t;
while(t--)
{
cin>>n;
for(int i = 0; i < n; i++)
{
cin>>arr[i];
}
staa[0] = arr[0];
endd[n-1] = arr[n-1];
for(int i = 1; i < n; i++)
{
staa[i] = gcd(staa[i-1], arr[i]);
}
for(int i = n-2; i >= 0; i--)
{
endd[i] = gcd(endd[i+1], arr[i]);
}
int maxx = -INF;
for(int i = 1; i <= n-2; i++)
{
maxx = max(maxx, gcd(staa[i-1], endd[i+1]));
}
maxx = max(maxx, max(staa[n-2],endd[1]));
cout<<maxx<<endl;
}
return 0;
}