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

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

 

请用c++的贪心算法来完成本题,代码禁止有注释 G 货币系统 作者 UESTC 单位 电子科技大学 给定一个长度为 n 的升序组 A,第 i 项的值为 A i ​ ,其中 A 1 ​ =1。 用这个组构建一个货币系统,对于任意正整 x,定义换钱张为 f(x,n),其中 n 为组长度。这个函表示使用这一套货币系统支付 x 元时,如果要满足尽量先拿大面额纸币再拿小面额纸币的原则,需要拿出多少张纸币。对于任意正整 x 和一个正整 y∈[1,n],f(x,y) 满足: f(x,y)={ ⌊ A y ​ x ​ ⌋+f(xmodA y ​ ,y−1) x ​ y>1 y=1 ​ 你需要处理 q 组询问,每一组询问会给出一个整 m,请回答有多少个正整 x 满足 f(x,n)=m。 输入格式: 输入第一行有两个正整 n 和 q(1≤n≤10 5 ,1≤q≤10 6 ),表示组 A 的长度和询问次。 第二行有 n 个正整 A 1 ​ ,A 2 ​ ,…,A n ​ (1=A 1 ​ <A 2 ​ <…<A n ​ ≤10 6 ),表示组 A。 第三行有 q 个整 m 1 ​ ,m 2 ​ ,…,m q ​ (1≤m i ​ ≤10 9 ),其中 m i ​ 表示第 i 次询问的整。 输出格式: 输出一行 q 个用空格隔开的整,第 i 个整表示第 i 次询问的答案。 输入样例: 6 2 1 5 10 20 50 100 1 2 输出样例: 6 18 样例解释 对于样例,给出的货币系统中纸币面额有 1 元、5 元、10 元、20 元、50 元和 100 元六种。按照规则,当你要支付 6 元时只能拿出两张纸币,即一张 1 元和一张 5 元,也就是 f(6,6)=2。虽然支付 6 元也可以使用六张 1 元,但是这种方案并不满足尽量拿大面额纸币的原则,也不满足本题函的定义。 代码长度限制 50 KB Java (javac) 时间限制 2000 ms 内存限制 512 MB Python (python3) 时间限制 2000 ms 内存限制 512 MB Python (pypy3) 时间限制 2000 ms 内存限制 512 MB 其他编译器 时间限制 1000 ms 内存限制 512 MB 栈限制 131072 KB
最新发布
10-03
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值