寒假私训——二分 B - Aggressive cows

进击的野牛

题目描述

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

解题思路

要判断一个题能否用二分算法,首先要找出搜索范围,然后根据题意,判断要找的值是小于X的最大值还是大于x的最小值。这种类型题的思路都很明确,但是如果没有处理好数据,很容易出错。这个题的思路和前面的一样,要找的是小于X最大的数,保留左部:

代码

#include <stdio.h>
#include<algorithm>
#define maxn 1000000
#define M 1e9+5
using namespace std;
typedef long long ll;
ll num1,de;
ll p[maxn];
ll L,R,mid;
bool check(ll x)
{
    int num2=p[0];
    int sum=1;
    for(int i=1;i<num1;i++)
    {
        if(p[i]-num2>=x)
        {
            num2=p[i];
            sum++;
        }
    }
    if(sum>=de)
        return 1;
    else
        return 0;
}
int main()
{
    while(~scanf("%lld%lld",&num1,&de))
    {
        for(int i=0;i<num1;i++)
        {
            scanf("%lld",&p[i]);
        }
        sort(p,p+num1);
        R=p[num1-1]-p[0];
        L=0;
        while(R-L>1)
        {
            mid=(R+L)/2;
            if(check(mid))
                L=mid;
            else
                R=mid;
        }
        printf("%lld\n",L);
    }
    return 0;
}
发布了36 篇原创文章 · 获赞 1 · 访问量 1400

猜你喜欢

转载自blog.csdn.net/atnanajiang/article/details/104016860
今日推荐