POJ 2456 Aggressive cows(二分+贪心)

来源:互联网 发布:ubuntu开机启动项 编辑:程序博客网 时间:2024/05/16 09:51

Aggressive cows
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 16273 Accepted: 7784

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 312849

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.

代码:

#include<stdio.h>  #include<math.h>  #include<algorithm>  using namespace std;    int v[100010];    int main()  {      int n,c,i;      while(~scanf("%d%d",&n,&c))      {          for(i=0;i<n;i++)              scanf("%d",&v[i]);          sort(v,v+n);                    //隔间位置从小到大排序          int l=0,r=1000000000,mid;       //l为起点,r为终点,mid为中值          while(l<=r)          {              int cnt=1,pre=v[0];         //cnt记录距离大于中值时可养牛数,pre记录上个牛所在位置              mid=(l+r)/2;                //mid记录中值              for(i=1;i<n;i++)              {                  if(v[i]-pre>=mid)       //遍历所有位置得到可养牛数cnt                  {                      cnt++;                      pre=v[i];                  }              }              if(cnt<c)              {                  r=mid-1;              }              else              {                  l=mid+1;                //最后有两种情况            }                           //mid=ans=l=r   执行l+1        }                               //mid=l=r=ans+1 执行r-1        printf("%d\n",r);               //所以答案为r    }      return 0;  }