Aggressive cows

来源:互联网 发布:java设计模式 百度云 编辑:程序博客网 时间:2024/05/24 02:06

题目:

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 312849
样例输出
3
提示
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.

思路:

问题转换:最小值问题——》判断性问题

求最宽松圈养的最小距离——》判断这个距离是否刚好满足条件


#include<stdio.h> #include<algorithm>using namespace std;int stalls[100000];int N,cows;int check(int x){int num = cows;int position = stalls[0];num --;for(int i = 1;i < N;i ++){if(stalls[i] >= x + position){position = stalls[i];num --;}    if(num <= 0)break;}if(num <= 0){return 1;}elsereturn 0;}int main(){scanf("%d %d",&N,&cows);for(int i = 0;i < N;i++){scanf("%d",&stalls[i]);}sort(stalls,stalls+N);int l = 1,r = stalls[N-1] - stalls[0];int mid ;if(cows > 1)while (l <= r) {mid = (l+r)/2;        if (check(mid) == 1) {        l = mid+1;}        else r = mid-1;    }    else    {    printf("%d\n",0);    return 0;}printf("%d\n",l-1);return 0;}

0 0
原创粉丝点击