Poj 2456 Aggressive cows【贪心+二分】

来源:互联网 发布:linux递归创建目录 编辑:程序博客网 时间:2024/05/16 09:37

Aggressive cows
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 11430 Accepted: 5597

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.

Source

USACO 2005 February Gold

题目大意:

有n个地方,有m头牛,一头牛只能分配一个地方,问如何分配使得所有牛之间的距离最小的那个值最大,为多少?


思路:


1、首先我们队这个n个地方按照坐标升序排序。


2、然后我们考虑这样一个特性:随着我们枚举出来的答案越大,能够分配牛去居住的头数也会越小,那么其满足单调性(递减),那么我们可以二分查找这个最大值。


3、对应枚举出来的当前值mid,我们贪心的去分配牛去居住,首先我们在第一个地方直接放一头牛即可,对应设定pre表示上一头牛放在了哪个位子,那么我们下一头牛的地方分配需要满足pos-pre>=mid,而且我们想要分配更多的牛去居住,那么这个pos我们选择距离pre最近的那个即可。那么我们根据这个规则一直统计下去,看看当前mid值最多可以容纳多少头牛居住。对应枚举出来的这个当前值mid,如果可行(能够容纳的牛的数量大于等于m),那么当前mid值就是一个可行解,一直二分下去维护最后一个可行解输出即可。


Ac代码:

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int a[100050];int n,m;int Slove(int mid){    int pre=0;    int cont=1;    for(int i=1; i<n; i++)    {        if(a[i]-a[pre]>=mid)        {            pre=i;            cont++;        }        else continue;    }    if(cont>=m)return 1;    else return 0;}int main(){    scanf("%d%d",&n,&m);    for(int i=0; i<n; i++)    {        scanf("%d",&a[i]);    }    sort(a,a+n);    int ans;    int l=0;    int r=1000005000;    while(r-l>=0)    {        int mid=(l+r)/2;        if(Slove(mid)==1)        {            ans=mid;            l=mid+1;        }        else        {            r=mid-1;        }    }    printf("%d\n",ans);}



0 0
原创粉丝点击