Maximum Value CodeForces - 484B(区间最大余数)

题目传送门:http://codeforces.com/problemset/problem/484/B

B. Maximum Value

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

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.

Examples

input

Copy

3
3 4 5

output

Copy

2

思路:灵活应用algorithm中的函数—unique()和lower_bound(),想用sort将输进来数(假设为数组a)排序,再用unique去重(详细unique①),在进行倍数操作每一次进行倍数操作是用lower_bound()(详细看②),定位a数组中小于倍数的最大数的位置p,所以这里可以求出一个部分最大的余数ans再用max选出最大的ans。

①:http://www.cplusplus.com/reference/algorithm/unique/

②:加入a数组为1,2,3,4,5,6 。现在你想试试3能放到a数组中的那个位置p=lower_bound(a,a+6,3)-a(=2)(如果是upper_bound的话p=3),这样就能找出3在a中的位置且不改变a的值,如果希望改变a中的值可以lower_bound(a,a+6,3)=3,这样新来的3会代替原来的3,应为lower_bound和upper_bound的返回值是地址(注意不是数组下标)。

代码:

//https://vjudge.net/contest/222940#problem/D
#include<stdio.h>
#include<iostream>
#include<algorithm>
#define f(a,b) for(i=a;i<b;i++)

using namespace std;

int a[200005];

int main()
{
	int n,i;
	
	scanf("%d",&n);
	f(0,n) scanf("%d",&a[i]);
	sort(a,a+n);
	int sz=unique(a,a+n)-a;
//	f(0,sz) printf("%d  ",a[i]);
	
	int ans=0;
	f(0,sz)
	{
		int j;
		for(j=a[i]+a[i];j<=a[sz-1];j+=a[i])
		{
			int p=lower_bound(a,a+sz,j)-a;
			//printf("%d\n",p);
			ans=max(a[i]-j+a[p-1],ans);
		}
		int p=lower_bound(a,a+sz,j)-a;
		ans=max(a[i]-j+a[p-1],ans);
	}

	printf("%d",ans);
	
	return 0;
}

欢迎指出错误。。。。谢谢 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值