HDU - 6025 Coprime Sequence ʕ •ᴥ•ʔ

Do you know what is called ``Coprime Sequence''? That is a sequence consists of 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.

InputThe first line of the input contains an integer , denoting the number of test cases. 
In each test case, there is an integer  in the first line, denoting the number of integers in the sequence. 
Then the following line consists of  integers , 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之后,在用这个gcd与另一个数求新的gcd,在用新的gcd与其他的数求一个新新的gcd........如此反复,知道弄完整个数列,最后得到的就是整个数列的gcd.

所以你可以知道求一个数列的gcd没有顺序之说,随便选那个数开始都可以。

这样我们就很好处理了:

设所求数列为a;

h1[i] 是a[i] 前面所有数字的gcd;

h2[i] 是a[i]  后面所有数字的gcd.

删除a[i]之后,新的数列的gcd就是gcd(qian[i-1], hou[i+1]);所以我们只需要遍历一下就可以求出最大的了.

#include <cstring>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string.h>
//#include <map>
#include<vector>
#define ll long long
using namespace std;
#define pai acos(-1,0)
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n;
		cin>>n;
		int h1[100010];//前i项GCD的值 
		int h2[100010];//后i项GCD的值
		int a[100010];
		memset(h1,0,sizeof(h1));
		memset(h2,0,sizeof(h2));
		int maxx;
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
		}
		h1[1]=a[1];
		for(int i=2;i<=n;i++)
		{
			h1[i]=__gcd(a[i],h1[i-1]);
		}
		h2[n]=a[n];
		for(int i=n-1;i>=1;i--)
		{
			h2[i]=__gcd(h2[i+1],a[i]);
		}
		int ans=0;
		
		for(int i=1;i<=n;i++)
		{
			if(i==1)
				ans=max(ans,h2[i+1]);
			else if(i==n)
				ans=max(ans,h1[i-1]);
			else
				ans=max(ans,__gcd(h1[i-1],h2[i+1]));
		}
		printf("%d\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/henucm/article/details/82259289