Walking in the Forest (二分~最小化最大值)

链接: https://www.nowcoder.com/acm/contest/106/K
来源:牛客网

题目描述

It’s universally acknowledged that there’re innumerable trees in the campus of HUST.

Now you're going to walk through a large forest. There is a path consisting of N stones winding its way to the other side of the forest. Between every two stones there is a distance. Let d i indicates the distance between the stone i and i+1.Initially you stand at the first stone, and your target is the N-th stone. You must stand in a stone all the time, and you can stride over arbitrary number of stones in one step. If you stepped from the stone i to the stone j, you stride a span of (d i+d i+1+...+d j-1). But there is a limitation. You're so tired that you want to walk through the forest in no more than K steps. And to walk more comfortably, you have to minimize the distance of largest step.

输入描述:

 
 
The first line contains two integer N and K as described above.
Then the next line N-1 positive integer followed, indicating the distance between two adjacent stone .

输出描述:

An integer, the minimum distance of the largest step.

                    这道题就是一道二分~最小化最大值的模板题~~

                   到时要注意几个细节~~:

                   1.sum会爆int ;

                   2. 用li < ri 的情况下可能会使最后的不经过检测;

                   3.li初始化为1,而又没有考虑一步不能跨过的情况;

#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
long long int m[100005];	
int n, k;
int check(long long int mid)
{
	long long int sum = 0;
	int cnt = 1;
	for (int s = 0; s < n; s++)
	{
		if (m[s] > mid)
		{
			return 0;
		}
		sum += m[s];
		if (sum > mid)
		{
			sum = m[s];
			cnt++;
		}
	}
	if (cnt > k)
	{
		return 0;
	}
	return 1;
}
int main()
{
	cin >> n >> k;
	n--;
	long long int sum = 0;
	for (int s = 0; s < n; s++)
	{
		scanf("%lld", &m[s]);
		sum += m[s];
	}
	long long int ans = sum;
	long long int li = 0, ri = sum;
	while (li <= ri)
	{
		long long int mid = (li + ri) / 2;
		if (check(mid))
		{
		    ans = mid;
			ri = mid - 1;
		}
		else
		{
             li = mid+1;
		}
	}
	cout << ans << endl;
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值