poj 2456 Aggressive cows

来源:互联网 发布:出入无时 莫知其乡解释 编辑:程序博客网 时间:2024/06/05 12:50
/*DescriptionFarmer 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, xiOutput* Line 1: One integer: the largest minimum distanceSample Input5 312849Sample Output3题意:有n间牛舍,排成一条直线,位置分别为xi。有m头牛对小屋很不满意,因此经常互相攻击,为了防止这些牛互相伤害,所以要求这些牛的牛舍距离尽可能远。也就是要最大化最近的两头牛之间的距离 要求他们之间的距离最大,可以二分距离记为c,然后从距离最近的牛舍开始,安排距离大于c的牛舍住,如果安排不下,则说明距离太大,二分左半部分,否则二分右半部分*/#include <stdio.h>#include <algorithm>using namespace std;#define INF 0x3f3f3f3fint n,m;int room[100005];bool fun(int x){int num=1;//第一个牛舍必须要放一头牛,这样对于后面几头牛选择更多一些 int i;int c,lt;lt=0;for(i=1;i<m;i++){c=lt+1;while(c<n&&room[c]-room[lt]<=x)c++; if(c==n)//如果条件不符合并且已经到达最后的位置了,那么说明x不符合条件 return false;lt=c;  }  return true;}int main(){int i;while(scanf("%d%d",&n,&m)!=EOF){for(i=0;i<n;i++){scanf("%d",&room[i]);}sort(room,room+n);int first=0;int last=INF;int mid;while(last-first>1){mid=(last+first)/2;if(fun(mid))first=mid;elselast=mid;}printf("%d\n",last);}return 0;}

0 0