百练2456 Aggressive cows&典型二分

来源:互联网 发布:中级程序员面试题 编辑:程序博客网 时间:2024/05/17 06:09
2456:Aggressive cows
总时间限制: 1000ms 内存限制: 65536kB
描述
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 3
1
2
8
4
9
样例输出
3
#include<iostream>#include<algorithm>#include<cstdio>using namespace std;int n,c;int a[1000005];bool ok(int x) //判断函数{    int i,res,la;    res=1; la=0; i=1;    while(i<n)    {while(a[i]-a[la]<x) i++;if(i<n) res++;  //是否出界的判断!if(res>=c) return true;la=i;i++;     }   return false; }int main(){        int i,l,r,mid,ans=0;        scanf("%d%d",&n,&c);for(i=0;i<n;i++) scanf("%d",&a[i]);sort(a,a+n); //排序l=0; r=1000000000; while(l<=r){mid=(l+r)/2;if(ok(mid)){ans=mid; l=mid+1;}else r=mid-1;}printf("%d\n",ans);return 0;}

原创粉丝点击