Aggressive cows

5 篇文章 0 订阅
/*
挺水的贪心, 关键之处在于STL式的upper_bound贪心思路
另外check函数的第一个虚拟地址, 也是比较好理解的
*/
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cstdio>
#include <cmath>
typedef long long ll;
typedef unsigned int Rank;
typedef unsigned long long ull;
using namespace std;
const int MAXN = 100100;
int rooms[MAXN];
int N, C;
bool check(int dist){
    int previous_pos = rooms[0] - rooms[N - 1] - 10;// 第一次位置定在很远的前面, 是虚拟的, 为了方便判断
    int rest_cows = C;
    // printf("DEBUG\t""%d %d %d\n", dist, previous_pos, rest_cows);
    for(int i = 0; i < N && rest_cows; ++i){// 注意牛都安排好了可以退了, 这里写成||的话, 就会访问到非法的随机位置
        if(rooms[i] >= previous_pos + dist){// 如果当前房间可以使用, 就更新previous——pos(上一个位置)
            previous_pos = rooms[i];
            // printf("%d ", previous_pos);
            --rest_cows;// 剩余的未安排的牛的数量减一
        }
    }
    return rest_cows == 0;// <= 0也可以
}
int main()
{
    while(scanf("%d%d", &N, &C) != EOF){
        for(int i = 0; i < N; ++i){
            scanf("%d", rooms + i);
        }

        sort(rooms, rooms + N);

        int lo = 0, hi = rooms[N - 1] - rooms[0] + 1;
        int len = hi - lo, half, mi;
        while(len > 0){
            half = len >> 1;
            mi = lo + half;
            if(check(mi)){
                lo = mi + 1;
                len = len - half - 1;
            }
            else
                len = half;
        }
        printf("%d\n", lo - 1);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值