Poj 2456 Aggressive cows (二分逼近)

来源:互联网 发布:四维数据能分辨男女吗 编辑:程序博客网 时间:2024/05/20 04:51

题目链接:http://poj.org/problem?id=2456


Aggressive cows
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 11700 Accepted: 5727

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.

Source

USACO 2005 February Gold

[Submit]   [Go Back]   [Status]   [Discuss]



题目大意:n个牛棚,m头牛(m  <= n),将所有牛放入牛棚,使得最近的两头牛之间的距离最大(牛是具有攻击性的)

题目解析:二分逼近思想,先给a数组排序,距离范围为0~(a[n] - a[1]),二分枚举距离,判断是否能放下所有的牛,

                   放下时L=md + 1,放不下为 R= md - 1

                   借鉴大牛博客:http://blog.csdn.net/lyhvoyage/article/details/23261973


代码如下:


#include<iostream>#include<algorithm>#include<map>#include<stack>#include<queue>#include<vector>#include<set>#include<string>#include<cstdio>#include<cstring>#include<cctype>#include<cmath>#define N 100009using namespace std;const int inf = 1e9;const int mod = 1<<30;const double eps = 1e-8;const double pi = acos(-1.0);typedef long long LL;int a[N];int main(){    int n, m, i, j, k;    scanf("%d%d", &n, &m);    for(i = 1; i <= n; i++) scanf("%d", &a[i]);    sort(a + 1, a + 1 + n);    int l, r;    l = 0; r = a[n] - a[1];    while(l <= r)    {        int md = (l + r) >> 1;        k = 1;        int now = a[1];        for(j = 1; j <= n; j++)        {            if(a[j] - now >= md) k++, now = a[j];            if(k >= m) break;        }        if(k < m) r = md - 1; //不减1变成死循环        else l = md + 1; //不加1变成死循环    }    printf("%d\n", l - 1);    return 0;}


1 0