POJ 2456 Aggressive cows(贪心+二分)

来源:互联网 发布:纳什职业生涯数据 编辑:程序博客网 时间:2024/04/29 11:31

Aggressive cows
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 6948 Accepted: 3462

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.

题目大意:

给你x轴上的n个坐标,然后告诉你一个整数m,使得两个距离最近的点的距离最大(是不是有点晕,就是说比如1,2,4,8,9这5个点,当m==3的时候,在1,4,9各放一个牛,则最近的两个点是4,9那么他们之间的距离是5,是最大的了)


解题思路:

其实就是一道二分,定义好方程的状态然后在[0,inf]的区间内去寻找满足条件的解就OK了

定义C(d)表示的是可以安排牛的位置使得最近的两头内的距离不小于d、其实也就是说,使得任意两头牛的距离不小于d了。


然后我们利用贪心的方法就可以解决了。

1,现对于牛棚的坐标进行排序。

2,把第一头牛放在x[0]的位置。

3,如果第i头牛放入了第x[j]的位置,那么第i+1头牛就应该满足x[k]-x[j]>=d的最小的k中。。。。


代码:

# include<cstdio># include<iostream># include<algorithm># include<cstring># include<string># include<cmath># include<queue># include<stack># include<set># include<map>using namespace std;# define inf 999999999# define MAX 100000+4int a[MAX];int n,m;bool C ( int d ){    int last = 0;    for ( int i = 1;i < m;i++ )    {        int crt = last + 1;        while ( crt < n&& a[crt]  - a[last] < d )        {            crt++;        }        if ( crt == n )            return false;        last = crt;    }    return true;}int main(void){    while ( cin>>n>>m )    {        for ( int i = 0;i < n;i++ )        {            cin>>a[i];        }        sort(a,a+n);        int lb = 0,ub = inf;        while ( ub-lb > 1 )        {            int mid = ( lb+ub )>>1;            if ( C(mid) )                lb = mid;            else                ub = mid;        }        printf("%d\n",lb);    }return 0;}


0 0
原创粉丝点击