• Maximum Value (二分+思维枚举)


    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

    3
    3 4 5
    

    Output

    2
    

    发现纯暴力绝对不行的

    由于由于求的是余数

    因此只需要二分出对于小于每个倍数的最大值即可

    但是看似复杂度似乎很高 实则内层循环求和之后是ln(n)

    所以该算法分复杂度是o(n*log(n)*log(n))

    #include<cstdio>
    #include<map>
    #include<cstring>
    #include<iostream>
    #include<queue>
    #include<algorithm>
    using namespace std;
    int a[200005];
    int main()
    {
        int n;
        scanf("%d",&n);
        for(int i=1; i<=n; i++)
            scanf("%d",&a[i]);
        int MAX=0;
        sort(a+1,a+1+n);
        for(int i=1; i<=n; i++)
        {
            if(i==1||a[i]!=a[i-1])
            {
                for(int j=2;j*a[i]<=a[n];j++)
                {
                    int tmp;
                    tmp=lower_bound(a+1,a+1+n,j*a[i])-a;
                    MAX=max(MAX,a[tmp-1]%a[i]);
                }
                MAX=max(MAX,a[n]%a[i]);
            }
           // cout<<MAX<<endl;;
        }
        printf("%d
    ",MAX);
        return 0;
    }
    //caowenbo
    
  • 相关阅读:
    c++ this *this
    名称空间
    c++ 静态持续变量
    c++ 数组
    c++ 头文件
    实例化和具体化详解
    在linux下安装eclipse以及运行c++程序的安装步骤
    在centos (linux) 搭建 eclipse c++开发分环境
    Linux上使用Qt Creator进行C/C++开发
    使用Qt Creator 2.60编写C/C++程序
  • 原文地址:https://www.cnblogs.com/caowenbo/p/11852304.html
Copyright © 2020-2023  润新知