【二分】小鱼吃大鱼

链接

Luogu U138097

题目描述

有n个数,选择两个数a和b,使得max(a,b) % min(a,b)最大

思路

对于每一个数,就枚举它的倍数,然后每次找第一个比它小的数,更新答案即可

代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>

using namespace std;

int n, a[5000005], ans, tot, now;

void work(int x)
{
	for(int j = 1; a[x] * (j - 1) <= a[tot]; ++j)
	{
		int tt = a[x] * j;
		int p = upper_bound(a + 1, a + tot + 1, tt - 1) - a - 1;
		if(p == 0) continue; 
		int n1 = max(a[x], a[p]);
		int n2 = min(a[x], a[p]); 
		ans = max(ans, n1 % n2);
	}
}

int main()
{
//	freopen("18.in","r",stdin);
	scanf("%d", &n);
	for(int i = 1; i <= n; ++i)
		scanf("%d", &a[i]);
	if(n == 1) {
		printf("0");
		return 0;
	}		
	if(n <= 10000) {
		for(int i = 1; i < n; ++i)
			for(int j = 1; j <= n; ++j)
			{
				int x = max(a[i], a[j]);
				int y = min(a[i], a[j]);
				ans = max(ans, x - (x / y) * y);
			}
	}
	else {
		sort(a + 1, a + n + 1);
		tot = unique(a + 1, a + n + 1) - a - 1; 
		now = 1;
		if(tot == 1) {
			printf("0");
			return 0;
		}
		for(int i = tot; i >= 1; --i)
			work(i);
	}
	printf("%d", ans);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值