Codeforces Round #276 (Div. 1) B. Maximum Value(数论)

You are given a sequence a consisting of n integers. Find the maximum possible value of  (integer remainder of ai divided by aj), where 1 ≤ i, j ≤ n and ai ≥ aj.

Input

The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·105).

The second line contains n space-separated integers ai (1 ≤ ai ≤ 106).

Output

Print the answer to the problem.


分析:原来想着枚举ai然后找到数列中离ai/2最近的那些数更新答案然后狂WA....    

ai = k*aj + b 这样我们枚举aj和k,每次找到数列中最后一个小于k*aj的数来更新答案就可以了.

这样复杂度是双log,2^10^5可以接受。


#include <bits/stdc++.h>
#define MOD 1000000007ll
#define maxnode 250000
using namespace std;
int n,Max,ans,a[200005];
int main()
{
    scanf("%d",&n);
    for(int i = 1;i <= n;i++)
    {
        scanf("%d",&a[i]);
        Max = max(Max,a[i]);
    }
    sort(a+1,a+1+n);
    n = unique(a+1,a+1+n) - a - 1;
    for(int i = 1;i <= n;i++)
    {
        for(int j = 2*a[i];j <= Max+a[i];j+=a[i])
        {
            int pos = lower_bound(a+1,a+1+n,j) - a;
            if(pos != 1 && a[pos-1] > a[i]) ans = max(ans,a[pos-1] % a[i]);
        }
    }
    cout<<ans<<endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值