OpenJ_Bailian - 2456 : Aggressive cows

版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/uzzzhf https://blog.csdn.net/uzzzhf/article/details/89364821

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?

Input

* Line 1: Two space-separated integers: N and C 

* Lines 2..N+1: Line i+1 contains an integer stall location, xi

Output

* Line 1: One integer: the largest minimum distance

Sample Input

5 3
1
2
8
4
9

Sample Output

3

Hint

OUTPUT DETAILS: 

FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3. 

Huge input data,scanf is recommended.

农夫 John 建造了一座很长的畜栏,它包括N (2≤N≤100,000)个隔间,
这些小隔间的位置为x0,...,xN-1 (0≤xi≤1,000,000,000,均为整数,各不相同).
John的C (2≤C≤N)头牛每头分到一个隔间。
牛都希望互相离得远点省得互相打扰。
怎样才能使任意两头牛之间的最小距离尽可能的大,这个最大的 最小距离是多少呢?

结题思路:二分,处理好细节

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>

using namespace std;
typedef long long ll;
ll a[100005];//全局数组便于多个函数进行访问
int n,m;// n:隔间数 m:奶牛数

int f(int mid)  //查找距离为mid时能安排奶牛的个数
{
    int sum=0;
    int len=1; //能安排的牛的数目
    for(int i=1;i<n;i++) //从第二个隔间开始遍历
    {
        if((sum+(a[i]-a[i-1]))<mid)//当前距离不足以放入奶牛
        {
            sum+=(a[i]-a[i-1]);
        }
        else //可以放入奶牛
        {
            sum=0;
            len++;
        }
    }
    if(len<m) return false;//奶牛未安排完,不符合情况
    else return true; //所有的奶牛都应经安排了,符合情况
}


int main()
{
    int i;
    while(scanf("%d%d",&n,&m)==2)  // n:隔间数 m:奶牛数
    {
        for(i=0;i<n;i++)
        {
            scanf("%lld",&a[i]); // 输入隔间坐标
        }
        sort(a,a+n);//排序
        ll low=a[n-1]-a[0],high=a[n-1]-a[0];
        for(i=1;i<n;i++)
        {
            low=min(low,a[i]-a[i-1]);//找出相邻隔间的最小值
        }
        ll mid;
        while(low<=high)
        {
            mid=(low+high)/2;//优秀
            if(f(mid)) //满足情况
            {
                low=mid+1; //在右半个区间继续找
            }
            else
            {
                high=mid-1; //在左半个区间继续找
            }
        }
        printf("%lld\n",high);//最后输出high就是核心,想想为什么?
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/uzzzhf/article/details/89364821