HYSBZ-1734 愤怒的牛 题解*

题面:

Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,…,xN (0 <= xi <= 1,000,000,000). His C (2 <= C <= N) cows don’t like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
农夫 John 建造了一座很长的畜栏,它包括N (2 <= N <= 100,000)个隔间,这些小隔间依次编号为x1,…,xN (0 <= xi <= 1,000,000,000). 但是,John的C (2 <= C <= N)头牛们并不喜欢这种布局,而且几头牛放在一个隔间里,他们就要发生争斗。为了不让牛互相伤害。John决定自己给牛分配隔间,使任意两头牛之间的最小距离尽可能的大,那么,这个最大的最小距离是什么呢

输入

  • Line 1: Two space-separated integers: N and C
  • Lines 2…N+1: Line i+1 contains an integer stall location, xi
    第一行:空格分隔的两个整数N和C
    第二行—第N+1行:i+1行指出了xi的位置

输出:

  • Line 1: One integer: the largest minimum distance
    第一行:一个整数,最大的最小值

题目分析:

为了方便尝试将牛按特定距离放入牛栏中,我们先把输入的牛栏的位置排序.
这时先假设一个距离mid,尝试能否将牛以mid的最小距离完全放入牛栏.
尝试的方法为:
将第一只牛放到第一个牛栏,然后向后找到第一个与此牛栏的距离大于mid的牛栏,将下一只牛放入.
重复这样的操作.
如果牛栏被遍历完之后,牛还没有全部放入,则说明以mid为最小距离不能将牛完全放入.否则说明能放入.
如果能够放入,则继续尝试比mid大的数字
如果不嫩放入,则尝试比mid小的数字
直到找到一个数字ans,使得以ans为最小距离时可以放入牛栏,而以ans+1为最小距离时不嫩完全放入牛栏.
这里用二分来实现.
排序之后可以知道,距离最远的两个牛栏为x1和xN.
然后我们查找一个mid,使得以mid为最小距离时,刚好不嫩放入牛栏.
所以假设left = 1, right = aN-a1, mid = (right + left)/2
当发现mid可以放入时,left = mid+1(因为), mid = (left + right)/2
否则right = mid-1, mid = (left + right)/2
在这个过程中,一旦发现一个mid能够放入牛栏,则把ans的值更新为mid.
到最后right = left时,mid = left = eight = 刚好不嫩放入牛栏的最小距离
此时ans为能完全放入牛栏的最大最小距离.

代码:

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

long n, c, l, r, a[100001], mid, ans;
//尝试将牛以i为最小距离放入牛栏
bool check(int i){
        long j = 1, pre = a[0], next;//j为已经放入的牛的个数,pre为放入第j头牛的牛栏
        next = lower_bound(a, a+n, pre + i) - a;//找到下一头牛的牛栏,即编号大于pre+i的牛栏,如果没有找到,next=0.
        while(next != n){//如果next=0,则说明牛栏已经用完.
              pre = *(lower_bound(a, a+n, pre+i));
              j++;
              next = lower_bound(a, a + n, pre + i) - a;
        }
        return (j >= c);//如果牛栏用完之后,已经放入的牛的数量大于应该放入的牛的数量,那么说明以i为最小距离可以把牛完全放入牛栏,返回true,否则返回false.
}

int main(){
        while(scanf("%ld%ld", &n, &c) != EOF){
        for(long i = 0; i < n; i++) scanf("%ld", &a[i]);
        sort(a, a+n);
        l = 1;
        r = a[n-1] - a[0];
        while(l <= r){
                mid = (l + r)/2;
                if(check(mid)){
                        ans = mid;//一旦mid能够符合,则ans = mid
                        l = mid + 1;
                }else{
                        r = mid - 1;
                }
        }
        printf("%ld\n", ans);
        }
}

猜你喜欢

转载自blog.csdn.net/qq_25807093/article/details/86701824