CodeForces - 484B 最大余数

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

 
 

思路:刚看到这个题一脸懵逼   现在终于明白喽

对数组先排序 从小到大遍历 对于每个数a, 对他取余最大的那个数一定是在他的倍数左面最靠近他的那个数 比如 对4来说( 8-1)( 12-1) ( 16-1)/...........结果最大

还有一神器

函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置

举例如下:(有序数组)

一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标

pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number数组的下标为0的位置。

pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number数组的下标为1的位置(即10所在的位置)。

pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number数组的下标为8的位置(但下标上限为7,所以返回最后一个元素的下一个元素)

所以,要记住:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!~

返回查找元素的第一个可安插位置,也就是“元素值>=查找值”的第一个元素的位置

upper-bound返回 大于插入值的第一个下标

再让我用通俗的语言讲一遍吧:lower-bound(  x1, x2, x3)一共三个参数 ,x1为首地址  x2为末地址, x3为要查找的数值  但他是在左闭右开的区间查找, 所以如果有下标从0开始的一个数组   lower-bound( a, a+n, x3)才是在整个数组内查询   因为a为a[0]的地址  而a[n-1] 的地址为a+n-1  所以如果查询不到符合的数值   则应该返回数组最后的下标加1  已经越界了  在这里即返回n.    加入有数组1 2 3 4 5 6 7   下标从1开始 

lower-bound( a+1 , a+1 + 7 , 8 )时返回8

端上代码来



#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <algorithm>
#include <queue>
using namespace std;
#define maxn 200005
int a[maxn];
int main()
{
    int n;
    int i , j ;
    while( scanf("%d", &n ) != EOF)
    {
        memset( a,0 , sizeof( a ));
        for( i  = 1; i<=n; i++)
        {
            scanf("%d", &a[i]);
        }
        sort( a+1, a+n+1);
        int t;
        int ans = 0;
        for( i =  1; i<=n; i++)
        {
            if( a[i] == a[i-1])
                continue;
            for( j = 2*a[i]; j<=a[n]; j = j+a[i])
            {
               t = lower_bound( a+1, a+n+1, j )-a;
               ans = max( ans, a[t-1]%a[i]);
            }
            ans = max( ans, a[n]%a[i]);///( 是不是也有点不懂 让我来为你解释哦 )防止这个数的某倍数
            ///不在数组内,而没办法进入第二层循环,出现最后一个数模他
            ///会结果很大的情况而被忽略 比如 2 3 4 5 6 7 ( 4 的2倍没有 但不能忽略7%4 这个大的!)
        }
        printf("%d\n", ans);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值