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

版权声明:随意转载 https://blog.csdn.net/nuiniu/article/details/81352947

题目传送门: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;
}

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

猜你喜欢

转载自blog.csdn.net/nuiniu/article/details/81352947