51nod最大mod值 1421

题意:

1421 最大MOD值
1.0 秒 131,072.0 KB 80 分 5级题
有一个a数组,里面有n个整数。现在要从中找到两个数字(可以是同一个) 𝑎𝑖,𝑎𝑗,使得ai mod aj最大并且ai >= aj

输入
单组测试数据。
第一行包含一个整数n,表示数组a的大小。(1 ≤ n ≤ 2*10^5)
第二行有n个用空格分开的整数ai (1 ≤ ai ≤ 10^6)。
输出
输出一个整数代表最大的mod值。
输入样例
3
3 4 5
输出样例
2

思路:

首先,ai % aj是最大的且ai >= aj,暴力的话复杂度是n^2的,那么肯定会T掉的,所以,我们要进行优化。。。。

因为ai % aj最大,所以ai一定是离aj的倍数最近的值,所以我们就枚举aj的倍数,虽然看着可能会T掉,但是实际上不会的。。。。

1 + 1/2 + 1/3 + 。。。。 1/n =ln(n) + C

注意:条件的判断,一定要满足a[id] > a[i]

代码实现:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<vector>
#include<cstdlib>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 1e6 + 5;
const double pi = acos(-1.0);

int n;
int a[maxn];

int main(){
	scanf("%d",&n);
	for(int i = 1;i <= n;i++){
		scanf("%d",&a[i]);
	}
	sort(a + 1,a + 1 + n);
	int tot = unique(a + 1,a + 1 + n) - a - 1;
	int ans = 0;
	for(int i = 1;i <= tot;i++){
		for(int j = 2;;j++){
			int now = a[i] * j;
			int id = lower_bound(a + 1,a + 1 + tot,now) - a;
			if(a[id] > a[i]) ans = max(ans,a[id]%a[i]);
			if(a[id - 1] > a[i]) ans = max(ans,a[id - 1]%a[i]);
			if(a[id + 1] > a[i])ans = max(ans,a[id + 1]%a[i]);
			if(now > a[tot]) break;	
		}
	}
	printf("%d\n",ans);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值