码迷,mamicode.com
首页 > 编程语言 > 详细

Codeforces 484B Maximum Value(排序+二分)

时间:2014-11-10 13:51:27      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   os   sp   for   strong   

题目链接:

         http://codeforces.com/problemset/problem/484/B

题意:

        求a[i]%a[j] (a[i]>a[j])的余数的最大值

分析:

       要求余数的最大值很明显a[i]越接近a[j]的倍数则余数越大 ,因此我们将所有的元素从大到小排序 ;

 然后枚举a[j]的倍数 ,二分查找小于a[i]倍数的最大值,然后更新余数的最大值。

代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

int a[200010];

inline int mymax(int a,int b){
    return a > b? a: b;
}


inline int bin_search(int l,int r,int val)//二分查找小于val的最大值
{
    int mid;
    while(l<=r){
        mid=(l+r)>>1;
        if(a[mid]==val) return mid-1;
        else if(a[mid]>val) r=mid-1;
        else l=mid+1;
    }
    return r;
}

int main()
{
    int n;
    while(~scanf("%d",&n)){
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        sort(a,a+n);
        int mmax = 0;
        for(int i=0;i<n-1;i++){
            if(a[i]==0||a[i]!=a[i-1]){//剪枝。如果之前出现过了就不用查了;
            int tmp=a[i]+a[i];
            while(tmp<=a[n-1]){
                int pos=bin_search(0,n-1,tmp);
                mmax = mymax(mmax,a[pos]%a[i]);
                tmp+=a[i];
            }
            mmax =mymax(mmax,a[n-1]%a[i]);
            }
        }
        printf("%d\n",mmax);
    }
    return 0;
}



Codeforces 484B Maximum Value(排序+二分)

标签:style   blog   http   io   ar   os   sp   for   strong   

原文地址:http://blog.csdn.net/bigbigship/article/details/40979191

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!