poj 2456 Aggressive cows && nyoj 疯牛 最大化最小值 二分

本文介绍了一种使用二分搜索算法解决 Aggressive Cows (疯牛) 问题的方法。通过在预排序的牛棚位置上应用二分搜索,找到能够放置 m 头牛的最大最小距离。代码实现展示了如何检查给定距离下是否可以放置所有牛。

poj 2456 Aggressive cows && nyoj 疯牛 最大化最小值 二分

题目链接:

nyoj : http://acm.nyist.net/JudgeOnline/problem.php?pid=586
poj : http://poj.org/problem?id=2456

思路:

二分答案,从前到后依次排放m头牛的位置,检查是否可行

代码:
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
const int maxn = 1e5+5;
const int INF = 1e9;
int a[maxn];
int n,m;
bool check(int d) {
    int pos,pre;
    pre=0;
    for(int i=0;i<m-1;++i) {
        pos=pre+1;
        while(pos<n&&a[pos]-a[pre]<d) {pos++;}
        if(pos==n) return false;
        pre=pos;
    }
    return true;
}
int main() {
    while(~scanf("%d %d",&n,&m)) {
        for(int i=0;i<n;++i) scanf("%d",&a[i]);
        sort(a,a+n);
        int l=0,r=INF,mid,ans;
        while(l<=r) {
            mid=(l+r)>>1;
            if(check(mid)) ans=mid,l=mid+1;
            else r=mid-1;
        }
        printf("%d\n",ans);
    }
    return 0;
}

转载于:https://www.cnblogs.com/lemonbiscuit/p/7928883.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值