HDU 6025 Coprime Sequence (前后缀+GCD)

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.

题意

给定含 n 个正整数的数组,求任意 n-1 个数的最大的 GCD。

解题思路

利用前缀、后缀快速解决。

pre[i] 表示前 i 个数的 GCD。

nxt[i] 表示第 i 个数(包含)之后所有数的 GCD。

则除第 i 个数之外的 n-1 个数的 GCD 为 __gcd(pre[i-1], nxt[i+1]) 。注意首尾特判即可。

代码

#include
using namespace std;
const int N = 100010;
int n, a[N], pre[N], nxt[N];
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        pre[1] = a[1];
        for(int i=2;i<=n;i++)
            pre[i] = __gcd(pre[i-1], a[i]);

        nxt[n] = a[n];
        for(int i=n-1;i;i--)
            nxt[i] = __gcd(nxt[i+1], a[i]);

        int ans = max(nxt[2], pre[n-1]);
        for(int i=2;i1], nxt[i+1]));
        printf("%d\n", ans);
    }
}

你可能感兴趣的:(HDU)