Aggressive cows POJ - 2456 (二分 最大化最小值)

在这里插入图片描述

题意: 输入N间屋子的坐标, 求最大的c头牛相邻之间的距离

题解: 非常经典的最大化最小值问题, 不难看出符合二分法的三要素: 判定条件, 范围, 单调.
确定判定函数check为, 判断所有两头牛之间的距离为d时是否可行, 贪心即可解, 每次取最近的距离外的牛
另外注意G++对cin和cout极其不友好, 用G++交的同学请把其改为scanf

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const LL maxn = 1e5+10;

int n, c, x[maxn];
bool check(int d)
{   //两头牛之间的距离为d时是否可行
    int last = x[1]+d, cnt = 1;
    for(int i = 2; i <= n; i++)
        if(x[i] >= last)
            last = x[i]+d, cnt++;
    return cnt >= c;
}
int main()
{
    cin >> n >> c;
    for(int i = 1; i <= n; i++)
        cin >> x[i];
    sort(x+1, x+1+n);
    int l = 0, r = x[n]-x[1];
    while(l+1 < r){ //防止死循环
        int mid = (l+r)/2;
        //cout << mid << endl;
        if(check(mid)) l = mid;
        else r = mid;
    }
    cout << l << endl;
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值