poj 2456

二分答案

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=1e5+9;
int a[maxn];
int n,m;
bool chk(int tmp)
{
    int t=1,ret=1;
    for(int i=2;i<=n;i++)
    if(a[i]-a[t]>=tmp)
    {
        t=i;
        ret++;
    }
    if(ret>=m) return true;
    else return false;
}

int main()
{
    while(scanf("%d %d",&n,&m)!=EOF)
    {
        for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
        sort(a+1,a+1+n);
        int l=0,r=1e9+9,mid;
        while(l<r)
        {
            mid=l+r+1>>1;
            if(chk(mid)) l=mid;
            else r=mid-1;
        }
        cout<<l<<endl;
    }
    return 0;
}


原文地址:https://www.cnblogs.com/riskyer/p/3293818.html