1. 程式人生 > >二分——Aggressive cows 憤怒的牛

二分——Aggressive cows 憤怒的牛

問題 A: Aggressive cows 憤怒的牛

時間限制: 5 Sec  記憶體限制: 64 MB
提交: 12  解決: 10
[提交][狀態][討論版][命題人:add_cy]

題目描述

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

第一行:一個整數,最大的最小值

樣例輸入

5 3
1
2
8
4
9

樣例輸出

3



(把牛放在1,4,8這樣最小距離是3 )

貪心+二分

最大值最小(最小值最大)可用二分法解決

1.對牛舍的位置x進行排序

2.把第一頭牛放在x0

3.如果把第i頭牛放入了xj間牛舍,那麼第i+1頭牛就要放入滿足xj+d<=xk的最小牛舍xk中,保證相鄰兩頭牛之間的距離>=d

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
int n,c,x[100005];
int judge(int d)//判斷距離為d時能否放下c頭牛
{
    int num=1;
    int temp=x[0]+d;
    for(int i=1;i<n;i++)
    {
        if(x[i]<temp)continue;//間距<d,繼續查詢
        temp=x[i]+d;//如果間距>=d,更新下一個牛舍的要求位置
        num++;//放下一頭牛
    }
    if(num>=c)return 1;//能放下c頭牛
    return 0;//不能放下c頭牛
}
int main()
{
    cin>>n>>c;
    for(int i=0;i<n;i++)
        cin>>x[i];
    sort(x,x+n);//從小到大排序
    int l=0,r=x[n-1]-x[n];//r表示最大距離
    while(l<=r)
    {
        int mid=(l+r)/2;//mid=l+r>>1;mid二分距離
        if(judge(mid))l=mid+1;//如果所求距離d>=mid,增大試探
        else r=mid-1;//如果所求答案d<mid,減小試探
    }
    cout<<r<<endl;
    return 0;
}