Coprime Sequence HDU - 6025

Do you know what is called ``Coprime Sequence''? That is a sequence consists of nnpositive 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 T(1T10)T(1≤T≤10), denoting the number of test cases. 
In each test case, there is an integer n(3n100000)n(3≤n≤100000) in the first line, denoting the number of integers in the sequence. 
Then the following line consists of nn integers a1,a2,...,an(1ai109)a1,a2,...,an(1≤ai≤109), 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;

qian[i] 是a[i] 前面所有數字的gcd;

hou[i] 是a[i]  後面所有數字的gcd.

刪除a[i]之後,新的數列的gcd就是gcd(qian[i-1], hou[i+1]);所以我們只需要遍歷一下就可以求出最大的了.

上代碼:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int gcd(int x,int y)
{
	return y==0 ? x : gcd(y,x%y);
}
int qian[100001];
int hou[100001];
int a[100001];
int main()
{
	int T;
	scanf("%d", &T);
	while(T--)
	{
		int n;
		scanf("%d", &n);
		qian[0] = 0;
		hou[0]  = 0;
		for(int i=1; i<=n; i++)
		{
		 	scanf("%d", &a[i]);
		}
		qian[1] = a[1];
		qian[2] = gcd(a[1],a[2]);
		for(int i=3; i<=n; i++)
		{
			qian[i] = gcd(qian[i-1],a[i]);
		}
		hou[n] = a[n];
	    hou[n-1] = gcd(a[n-1],a[n]);
		for(int i=n-2; i>=1; i--)
		{
		    hou[i] = gcd(a[i],hou[i+1]);	
		}	
	    int maxn = max(hou[2],qian[n-1]);
	    for(int i=2; i<=n-1; i++)
	    {
		  maxn = max(maxn, gcd(qian[i-1], hou[i+1]));	
		}
	    printf("%d\n",maxn);
	}
	return 0;
}

水波.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章