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;
}