首页 > 代码库 > 二分搜索的运用(1最大化最小值)

二分搜索的运用(1最大化最小值)

//#define LOCAL
#include<cstdio>
#include<algorithm>
using namespace std;
int const MAX_N=10005;
int const MAX_M=100;
int const INF=100000000;
int N,M,x[MAX_N],lb,ub;
//判断是否满足条件
bool C(int d)
{    
    int last=0;
    for(int i=1;i<M;i++)
    {
        int crt=last+1;
        while(crt<N&&x[crt]-x[last]<d)
        {
            crt++;
        }
        if(crt==N) return false;
        last=crt;
    }
    return true;
} 
void init()
{
    for(int i=0;i<N;i++)
    {
        scanf("%d",&x[i]);
    }
}
void solve()
{
    init();
    sort(x,x+N);
    lb=0,ub=INF;
    while(ub-lb>1)
    {
        int mid=(lb+ub)/2;
        if(C(mid)) lb=mid;
        else ub=mid;
    }
    printf("%d\n",lb);
}
int main()
{
#ifdef LOCAL
    freopen("Aggressive cows.in","r",stdin);    
    freopen("Aggressive cows.out","w",stdout);
#endif
    while(~scanf("%d%d",&N,&M))
    {
        solve();
    }
    return 0;
}

无限逼近