首页 > 代码库 > hdu4004 简单二分+贪心

hdu4004 简单二分+贪心


找到二分的左右值  然后对每一个中值进行判断     


#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;

int n,m,L;
int num[500010];
int abs(int a)
{
    return a<0?-a:a;
}
int max(int a,int b)
{
    return a>b?a:b;
}
int judge(int t)
{
    int star=0,sum=0,i=1;
    while(star<L)
    {
        for(;i<=n;i++)
        {
            if(star+t<num[i])
            {
                sum++;
                break;
            }    
        }
        star=num[i-1];
    }
    return sum;
}
int main()
{
    int i,j;
    while(~scanf("%d%d%d",&L,&n,&m))
    {
        int left=-1;
        num[0]=0;
        for(i=1;i<=n;i++)
        scanf("%d",&num[i]);
        num[++n]=L;
        sort(num+1,num+1+n);
        for(i=0;i<=n;i++)
        left=max(left,abs(num[i]-num[i-1]));
        int right=L;
        //printf("%d %d\n",left,right);
        int mid;
        while(left<=right)
        {
            mid=(left+right)/2;
            if(judge(mid)>=m) left=mid+1;
            else right=mid-1;
        }
        printf("%d\n",left);
    }        
    return 0;
}

hdu4004 简单二分+贪心