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.
解题思路:
最小值最大化问题,
用二分查找
最终的答案要满足的条件: 这个数时所有可能值中最大的一个, 所有的牛都能被放进隔间
枚举可能的值 ,看这个值是否就是要找的最大的最小值
对于枚举的最大的最短距离 mid, 看看是否能够让所有的牛都在隔间里,如果能,枚举一个更大的数 (二分法),
如果不能,就枚举一个更小的数(二分法)
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn = 100009;
int N, C;
int s[maxn];//隔间号
int dis[maxn];// 两相邻隔间的距离
bool Find(int mid)//假设最大的最短距离为mid这个值
{
int sum = 0;
int cnt = 1; //如果最大的最短距离为mid,那么总共可以放几头牛(即 两头牛之间的最短距离为mid时, 可以放几头牛)
for(int i = 1; i < N; i++)
{
if(sum + dis[i] < mid)
{
sum+= dis[i];
}
else
{
sum = 0;
cnt++;
if(cnt >= C)//如果最大的最短距离为mid时可以放下C头牛
{
return true;
}
}
}
return false;
}
int main()
{
while(cin >> N >> C)
{
for(int i = 1; i <= N; i++)
{
cin >> s[i];
}
sort(s + 1, s + N + 1);
for(int i = 1; i < N; i++)
{
dis[i] = s[i + 1] - s[i];
}
int High = s[N] - s[1]; //最后一个隔间到第一个隔间的距离为最大距离,两头牛的距离不会超过这个
int Low = s[N] - s[1];//暂定为这个值,随后好在相邻的隔间中找到 距离最小的那个距离是多少
for(int i = 1; i < N; i++)
{
Low = min(Low, dis[i]);
}
int mid ;
while(Low <= High)
{
mid = (Low + High) >> 1;//假设最大的最短距离为mid
if(Find(mid)) //如果最大的最短距离为mid时可以放下C头牛, 那么就去枚举更大一点的值,看看更大一点的最短距离能不能放下C头牛,如果能,那么这个更大一点的值就时更佳的答案
{
Low = mid + 1;
}
else
{
High = mid - 1;//如果最大的最短距离为mid时不能放下C头牛, 那么去枚举更小一点的值
}
}
cout << High << endl;
}
return 0;
}