[POJ 2456] 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?

输入

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

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

输出

* Line 1: One integer: the largest minimum distance

样例输入

5 3
1
2
8
4
9

样例输出

3

题解

#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;

int a[100005], n=0, c=0;
bool judge(int mid) {        
  int count=1, t=a[0];            // count畜栏计数器    
  for (int i=1; i<n; i++) 
    if (a[i]-t >= mid) {          // 选定的相邻两畜栏间距大于猜测距离,则更新计数器
      count++; t=a[i];
    }
 
  return count >= c;
}

int binarysearch() {              
  int l=0, r=a[n-1]-a[0];         // 左边界0,右边界为畜栏长度
  do {
    int mid = l + (r-l)/2;        // 防止溢出
    if (judge(mid)) l = mid+1;    // 左侧逼近
    else r = mid-1;               // 右侧逼近
  } while (l<=r);                 // 闭区间
  
  return l-1;                     
}

int main() {
  cin >> n >> c;                   
  for (int i=0; i<n; i++)
    cin >> a[i];
    
  sort(a,a+n);                        // 排序
  cout << binarysearch() << endl;     
  return 0;
}
发布了21 篇原创文章 · 获赞 8 · 访问量 1495

猜你喜欢

转载自blog.csdn.net/K_Xin/article/details/87863891
今日推荐