您的位置:首页 > 其它

CodeForces 484B 求最大余数

2015-08-24 09:20 387 查看
Description

You are given a sequence a consisting ofn integers. Find the maximum possible value of


(integer remainder ofai divided byaj), where1 ≤ 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 integersai (1 ≤ ai ≤ 106).

Output

Print the answer to the problem.

Sample Input

Input
3
3 4 5


Output
2


对于x来说,在k*x+1~(k+1)*x这段范围内,余数最大的肯定是最接近(k+1)*x的数,可以O(n)预处理出来距每个数最接近的那个数。然后通过枚举倍数的方法去遍历所有的k,这里复杂度约为O(n*logn)。

#include<iostream>
#include<cstdio>
#include<cstring>
#define INF 0x3f3f3f3f

using namespace std;

int Hash[2000010];
int dp[2000010];
int main()
{
int n;
while(~scanf("%d",&n))
{
memset(Hash,0,sizeof(Hash));

int Min=INF,Max=-1;
for(int i=0;i<n;i++)
{
int x;
scanf("%d",&x);
Hash[x]=1;
if(Min>x)
Min=x;
if(Max<x)
Max=x;
}

for(int i=Min;i<=2*Max+1;i++) //枚举出 所有的最靠近i的点 的大小
{
if(Hash[i-1])
dp[i]=i-1;
else
dp[i]=dp[i-1];
}

int MMax=-1;
for(int i=Min;i<=Max;i++)
{
if(Hash[i])
{
for(int j=i*2;;j+=i)   //枚举大小为i的k倍的点
{
if(dp[j]<i)
continue;
MMax=max(MMax,dp[j]%i); //枚举最靠近i的k倍的点.找出他们最大余数.
if(dp[j]==Max)
break;
}
}
}
printf("%d\n",MMax);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: