A - Aggressive cows OpenJ_Bailian - 2456 -二分搜索(最小值最大化)

  • A - Aggressive cows

  •  OpenJ_Bailian - 2456 

  • 最小值最大化

  • 我们假设x为最大的最小值,那么x-1是满足条件的,但他并不满足最大,x+1是不满足条件的。
  • 假设我们左边界是L,右边界是R,我们二分一个答案ans,ans为最后一个满足条件的数
  • 题意:农民约翰有用C只牛,然后他有N个隔间,每个隔间都有自己的坐标位置(一维的)pos。
  • 如何安排把牛安排进隔间才能使,所有牛之间距离的最小值最大,我们不需要求这个分配方案。
  • 我们只需要求这个最小距离的最大值,很裸的最小值最大化。
  • 思路:求出最小与最大的差距之后二分答案,在每一种枚举情况下回到序列中检验是否成立即可。
  • 二分过程为如果可以L继续去接近R,否则R来靠近L
  • #include<bits/stdc++.h>
    using namespace std;
    #define inf 0x3f3f3f3f
    #define maxn 100050
    #define ll long long
    ll n,c,a[maxn],l,r;
    bool check(int m)
    {
        ll t=c-1,pre=0;
        for(int i=1; i<n; i++)
        {
            if(a[i]-a[pre]>=m)
            {
                t--;
                pre=i;
            }
            if(t==0)break;
        }
        return t==0;
    }
    int main()
    {
        scanf("%lld%lld",&n,&c);
        for(int i=0; i<n; i++)
            scanf("%lld",&a[i]);
        sort(a,a+n);
        l=0,r=a[n-1]-a[0];
        while(l<r)
        {
            int m=(l+r+1)/2;
            if(check(m))l=m;
            else r=m-1;
        }
        cout<<r<<endl;
        return 0;
    }
    
  •  

猜你喜欢

转载自blog.csdn.net/BePosit/article/details/83926235