原题链接
Aggressive cows
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 11377 Accepted: 5576
Description
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.
题目的意思就是说有n个牛舍,牛与牛之间最小要隔开一定的距离,问这些牛与牛之间的最小距离的最大值是多少。那么我们如果设C(x)为判断牛与牛之间的距离的最大值可行不可行的话,如果所有的牛都保持这个距离而牛舍还没用完那么说明这个x是可以。而题目中就是要求满足C(x)的最大的x。
//http://poj.org/problem?id=2456
#include <algorithm>
#include <iostream>
#include <utility>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
const int MOD = int(1e9) + 7;
//int MOD = 99990001;
const int INF = 0x3f3f3f3f;
const ll INFF = (~(0ULL)>>1);
const double EPS = 1e-9;
const double OO = 1e20;
const double PI = acos(-1.0); //M_PI;
const int fx[] = {-1, 1, 0, 0};
const int fy[] = {0, 0, -1, 1};
const int maxn=100000 + 5;
int n,m;
int x[maxn];
bool can(int a){
int last=0,sum=1;
for(int i=1;i<n;i++){
if(x[i]-x[last]>=a){
last=i;
sum++;
if(sum>=m) break;
}
}
return sum>=m;
}
void solve(){
int l=0,r=INF;
//跳出循环时l+1=r,r不满足条件,但是l满足条件
while(r-l>1){
int mid=(l+r)/2;
if(can(mid)) l=mid;
else r=mid;
}
printf("%d\n",l);//题中要求最小距离中的最大值,即满足C(x)的最大x,所以这里就需要一个总是满足题目要求的l
}
int main(){
while(scanf("%d%d",&n,&m)==2){
for(int i=0;i<n;i++)
scanf("%d",&x[i]);
sort(x,x+n);
solve();
}
return 0;
}