暑期集训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;
}

 

全部评论

相关推荐

10-20 15:26
门头沟学院 Java
桥头牛油火锅:这个比例不正常,简历的话项目经历放中间,项目功能分点可以再明确点,前面加“·”或者“1 2 3”,另外简历上的照片可以去外面摄影店拍一下,以后也会用到的,hr筛人也是多少会看的,毕竟世界是一个巨大的卡颜局嘛,还有有些hr由于消息太多可能没看到,后面可能会回来找你,要简历的还会多一点,我也是普2本,比例大致是600:90:15:3,当然我实力不太够,拿的offer比较少,慢慢来吧
点赞 评论 收藏
分享
11-03 18:50
门头沟学院 Java
安远迢迢:问就是半年
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务