暑期集训2:ACM基础算法 例2:POJ-2456

2018学校暑期集训第二天——ACM基础算法

例二  ——   POJ - 2456

Aggressive cows

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 3
1
2
8
4
9

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.


题意:有n个牛栏,选m个放进牛,相当于一条线段上有 n 个点,选取 m 个点,使得相邻点之间的最小距离值最大。

思路:贪心+二分
    二分枚举相邻两牛的间距,判断大于等于此间距下能否放进所有的牛。


PPT中的代码如下:

#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<cstdio>
#include<cmath>
#include<set>
#include<map>
using namespace std;
const int N = 1000010;
int a[N], n, m;

bool judge(int k)	//枚举间距k,看能否使任意两相邻牛
{
    int cnt = a[0], num = 1;	//num为1表示已经第一头牛放在a[0]牛栏中
    for(int i = 1; i < n; i ++)	//枚举剩下的牛栏
    {
        if(a[i] - cnt >= k)	//a[i]这个牛栏和上一个牛栏间距大于等于k,表示可以再放进牛
        {
            cnt = a[i];
            num ++;	//又放进了一头牛
        }
        if(num >= m) return true;	//所有牛都放完了
    }
    return false;
}

void solve()
{
    int l = 1, r = a[n-1] - a[0];	//最小距离为1,最大距离为牛栏编号最大的减去编号最小的
    while(l < r)
    {
        int mid = (l+r) >> 1;
        if(judge(mid)) l = mid + 1;
        else r = mid;
    }
    printf("%d\n",r-1);
}
int main()
{
    while(~scanf("%d%d",&n,&m)){
        for(int i = 0; i < n; i ++)
            scanf("%d",&a[i]);
        sort(a, a+n);	//对牛栏排序
        solve();
    }
    
    return 0;
}

 

全部评论

相关推荐

沉淀一会:1.同学你面试评价不错,概率很大,请耐心等待; 2.你的排名比较靠前,不要担心,耐心等待; 3.问题不大,正在审批,不要着急签其他公司,等等我们! 4.预计9月中下旬,安心过节; 5.下周会有结果,请耐心等待下; 6.可能国庆节前后,一有结果我马上通知你; 7.预计10月中旬,再坚持一下; 8.正在走流程,就这两天了; 9.同学,结果我也不知道,你如果查到了也告诉我一声; 10.同学你出线不明朗,建议签其他公司保底! 11.同学你找了哪些公司,我也在找工作。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务