Maximum Value二分二分 暴力暴力

本文介绍了解决D-MaximumValue问题的两种方法,一种是通过枚举每个可能的最大值并寻找最大余数,另一种是使用二分查找来高效定位倍数位置并计算最大余数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

D - Maximum Value
Time Limit:1000MS    Memory Limit:262144KB    64bit IO Format:%I64d & %I64u

Description

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.

Sample Input

Input
3
3 4 5
Output
2

题意:就是让你求a[j] > a[i]下a[j]%a[i]的最大值
第一种思路:通常我们是对n个数进行暴力这样的话肯定会超时的,所以我们换个思路进行暴力,看每个数的最大为10^6,那么我们就从2到最大的开始枚举,输入的时候处理为在第几个数就是几,然后进行暴力,
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>

using namespace std;

int n;
int a[3000000];
int max1 = 2000000;

int main() {
    scanf("%d",&n);
    memset(a,0,sizeof(a));
    for(int i = 0; i < n; i++) {
        int d;
        scanf("%d",&d);
        a[d] = d;
    }
    for(int i = 2; i < max1; i++) {
        if(a[i] != i) {
            a[i] = a[i-1];
        }
    }//这个地方的处理就是说在找到a[i]的倍数的时候,确定他的前一位是最大比他小的数,
    int tol = 0;
    for(int i = 2; i < max1; i++) {
        if(a[i] == i) {
            for(int j = 2*i-1; j < max1; j += i) {
                if(a[j] > a[i]){
                  tol = max(tol,a[j]%a[i]);
                }
            }
        }
    }
    printf("%d\n",tol);
    return 0;
}
第二种思路是二分:每次找到a[i]的倍数大于等于的数的下标-1的数,然后进行判断最大余数
AC代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>

using namespace std;

int n;
int a[3000000];

int main() {
    scanf("%d",&n);
    memset(a,0,sizeof(a));
    for(int i = 0; i < n; i++) {
        scanf("%d",&a[i]);
    }
    sort(a,a+n);
    int tol = 0;
    for(int i = 0; i < n; i++) {
        if(i > 0 && a[i]==a[i-1]){
            continue;
        }
        int k = a[n-1]/a[i]+1;
        for(int j = 2; j <= k; j++) {
            int s = lower_bound(a+i,a+n,a[i]*j)-a-1;
            if(a[s]%a[i] > tol) {
                tol = a[s]%a[i];
            }
        }
    }
    printf("%d\n",tol);
    return 0;
}

二分二分,奇葩的东西!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值