luogu P1316 丢瓶盖 |二分答案

心不动则不痛 提交于 2019-12-04 07:57:04
题目描述

陶陶是个贪玩的孩子,他在地上丢了A个瓶盖,为了简化问题,我们可以当作这A个瓶盖丢在一条直线上,现在他想从这些瓶盖里找出B个,使得距离最近的2个距离最大,他想知道,最大可以到多少呢?

输入格式

第一行,两个整数,A,B。(B<=A<=100000)

第二行,A个整数,分别为这A个瓶盖坐标。

输出格式

仅一个整数,为所求答案。


一道练习二分的经典例题

#include<iostream>
#include<cstdio>
#include<algorithm>
#define ll long long
using namespace std;
ll f[100001];ll a,b;
bool check(ll x)
{
    ll ans=0,last=-(1<<30);
    for(int i=1;i<=a;i++)
    {
        if(f[i]-last>=x)
        {
        //  cout<<i<<" ";
            last=f[i];
            ans++;
            if(ans>=b)return 1;
        }
    }
    return 0;
}
int main()
{
    cin>>a>>b;
    ll ansmax=0;
    for(int i=1;i<=a;i++)
    {
        scanf("%lld",&f[i]);
        ansmax=max(ansmax,f[i]);
    }

    sort(f+1,f+a+1);
    ll l=0,r=ansmax+1;
    ll ans=0;
    while(l<=r)
    {
        ll mid=(l+r)/2;
        if(check(mid))
        {
            l=mid+1;
            ans=max(ans,mid);
        }
        else 
        r=mid-1;
    }
    cout<<ans;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!