Aggressive cows

来源:互联网 发布:qq农场魔法池守卫数据 编辑:程序博客网 时间:2024/05/13 15:00

Aggressive cows
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 7184 Accepted: 3578

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
思路:最大值最小化及最小值最大化的问题用二分写较快;

设c(x)表示满足条件的最小距离d,现在要求d的最大值

code:

#include<stdio.h>#include<iostream>#include<algorithm>using namespace std;int x[110000],m,n;bool c(int d){    int first=0;    for(int i=1;i<m;i++)//以牛的数量来控制次数,查找m-1次就行了x【0】是第一个确定的位置    {        int tem=first+1;        while(tem<n&&x[tem]-x[first]<d)//d为可安排牛位置的距离            tem++;            if(tem==n)        return false;        first=tem;    }    return true;}int main(){    int i,j,ans;    while(scanf("%d%d",&n,&m)!=EOF)    {        for(i=0;i<n;i++)            scanf("%d",&x[i]);        sort(x,x+n);        int lb=0,ub=1000000001;        while(ub-lb>1)        {            int mid=(lb+ub)/2;            if(c(mid))            {                lb=mid;               // cout<<"____"<<mid<<endl;            }            else            {                ub=mid;                //cout<<"******"<<mid<<endl;            }        }        printf("%d\n",lb);    }    return 0;}





0 0
原创粉丝点击