第十四届华中科技大学程序设计竞赛 K 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 di 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 (di+di+1+...+dj-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
输入
6 3
1 3 2 2 5
输出
5
【题意】:
题意就是说有n块石头,每块石头中间有一定的距离,一次可以跳过多个石头,但是不可以超过k步,求最大步的最小值 。
其实意思就是说,如果你每一步比较小,比如一块一块石头地过去,那么步数就太多了;但是如果你直接一步跳到最后,这样又太浪费体力了,而且不符合题意,而题意就是要你找到这么一个平衡点,可以恰好走到三步,然后求其中最大的一步的距离(相对于其他两步是最大的,但相对于所有情况的最大步它是最小的一种情况)
【出处】:POJ 3272 Monthly Expense
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <set>
#include <string>
#include <cstdlib>
#include <cmath>
using namespace std;
#define ll long long
#define mod 1000000007
int n, k;
ll a[100005];
int main() {
scanf("%d%d", &n, &k);
ll s = 0;
ll Max = 0;
for (int i = 1; i <= n - 1; ++i) {
scanf("%lld", &a[i]);
s += a[i];
Max = max(Max, a[i]);
}
ll l = Max, r = s, ans, mid;
while (l <= r) {
mid = (l + r) >> 1;
s = 0;
int c = 0;
for (int i = 1; i <= n - 1; ++i) {
s += a[i];
if (s > mid) { //多个跳不过,只能前面算跳一次,从这里重新开始跳
s = a[i];
c++;
}
}
if (c >= k) {
l = mid + 1;
}
else {
r = mid - 1;
ans = mid;
}
}
cout << ans << endl;
return 0;
}