poj3258 二分好题,最大化最小值

题意:一头牛,要过L这么宽河,河中有n个石墩,牛要从上面跳过去;
现在给你m次移除石墩的机会,要你移除后使得每两点之间的距离最大,并输出它;

理解:
开始我觉得把整个距离之差弄出来看看,发现有的石墩计算后就不能计算了,但是一直找不到好方法去移除它;
于是我用了一个set,结果直接超时。。。
然后我就想了很久,发现可以记录下不该用的石墩之前的距离总和sum;
即如果前面的石墩不能用就加到sum里,否则sum归0;
然后在找的时候用二分去枚举答案,更新到不能更新为止;

代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
#include <set>
#include <cmath>

using namespace std;

#define maxn 100100
#define x first
#define y second
#define ll long long
#define P pair<ll, ll>
#define INF 1e9

int a[maxn];

bool solve(int x, int n, int m)
{
    int count = 0;
    /*set<int> st;   //超时的地方,想的太天真了。
    for (int i = 0; i < n; ++i)
    {
        st.insert(a[i]);
    }
    set<int> :: iterator it;
    for (it = st.begin(); it != st.end(); ++it)
    {
        if (it == st.begin()) ++it;
        set<int> :: iterator i;
        i = it;
        --it;
        set<int> :: iterator j;
        j = it;
        if (*i - *j < x)
        {
            st.erase(*i);
            ++count;
        }
        else ++it;
    }*/
    int sum = 0;   //记录下前面应该移除石墩到不该移除的石墩的距离;
    for (int i = 1; i < n; ++i)
    {
        if (sum + (a[i] - a[i - 1]) < x)  //判断是否该移除;
        {
            sum += a[i] - a[i - 1];
            ++count;
        }
        else sum = 0;
    }
    if (count <= m) return false;
    else return true;
}

int main()
{
    int l, n, m;
    scanf("%d%d%d", &l, &n, &m);

    a[0] = 0;
    a[n + 1] = l;
    for (int i = 1; i <= n; ++i)
    {
        scanf("%d", &a[i]);
    }
    sort(a, a + n + 2);

    if (m == 0)
    {
        int ans = INF;
        for (int i = 1; i < n + 2; ++i)
        {
            if (a[i] - a[i - 1] < ans)
                ans = a[i] - a[i - 1];
        }
        printf("%d\n", ans);
        return 0;
    }

    if (m == n)
    {
        printf("%d\n", l);
        return 0;
    }

    int lb = 0, rb = l;
    while(rb - lb > 1)   //二分
    {
        int mid = (rb + lb) / 2;
        if (solve(mid, n + 2, m))
        {
            rb = mid;
        }
        else
        {
            lb = mid;
        }
    }
    printf("%d\n", lb);

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值