POJ 3258 River Hopscotch

白皮书上的课后习题,最大化最小值,典型二分搜索的应用。从石子中去掉若干个,使得剩下的石头间距的最小值最大。第一次卡在不知道如何判断某答案是否符合。后来发现除了常规思路考虑如何去掉其中若干个之外,也可以反向思考,如何放置剩余的石头。另,二分搜索有时候边界条件容易出错,推荐写成左闭右闭区间。

/*POJ 3258 River Hopscotch
Main thoughts: use binary search to maximize the minimum
Difficulty for me :
1. cant figure out how to count the number of the removed rock
2. not very clear about the next operation after binary search
there are two methods to do:
1. instead of considering how to remove, thinking about how to put the remain N-M rocks
2. use a count to record the number, instead of using M inside of the loop, it's really convenient to record.
*/
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
int L, N, M;
int a[50010];
//  second method count the number that need to be removed by order
int binarysearch(int low, int high) {
    while (low <= high) {
        int mid = (low + high) / 2;
        int count = 0;
        int s = 0, e = 1;
        while (e < n) {
            if (d[e] - d[s] >= mid)
                s = e, e += 1;
            else 
                e += 1, count += 1;
        }
        if (count > m)
            high = mid - 1;
        else
            low = mid + 1;
    }
    return high;
}
//  first method, just consider how to put the remaining rocks, if reaches the end, return false
bool check(int n)
{
	int last = 0;
	for (int i = 1; i < N - M; i++)
	{
		int current = last + 1;
		while (current < N && a[current] - a[last] < n)
		{
			current++;
		}
		if (current == N)
		{
			return false;
		}
		last = current;
	}
	return true;
}
int main()
{
	scanf("%d%d%d", &L, &N, &M);
	for (int i = 1; i <= N; i++)
		scanf("%d", &a[i]);
	a[++N] = L;
	++N;
	sort(a, a + N);
	// for (int i = 0; i <= N; i++)
	// 	printf("%d\n", a[i]);
	int lb = 0, ub = L + 1;
	while (ub - lb > 1)
	{
		int mid = (lb + ub) / 2;
		if (check(mid))
			lb = mid;
		else
			ub = mid;
	}
	printf("%d\n", lb);
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值