题目描述
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(1 ≤ K ≤ N ≤ 105) as described above.
Then the next line N-1 positive integer followed, indicating the distance between two adjacent stone(1 ≤ ai ≤ 105).
输出描述
An integer, the minimum distance of the largest step.
示例
输入
6 3
1 3 2 2 5
输出
5
题目大意
找到 k 步数之内能够到达第 n 块石头的最大步长的最小值。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+10;
int n,k;
ll d[maxn],sum,cnt;
int check(ll mid)
{
sum=0,cnt=0; // sum 用来记录一次可以跳的距离,cnt 用来记录跳的次数
for(int i=1;i<n;i++){
if(d[i]>mid){ // 两个石头之间的距离大于 mid,返回 0
return 0;
}
if(sum+d[i]>mid){
cnt++;
sum=0;
}
sum+=d[i];
}
if(sum){
cnt++;
}
return cnt<=k; // 当需要跳的次数大于 k 时,返回 0,反之,返回 1
}
int main()
{
cin>>n>>k;
for(int i=1;i<n;i++){
cin>>d[i];
}
ll l=1,r=1e10+5; // 左右边界
while(l<r){
ll mid=(l+r)/2;
if(check(mid)){
r=mid;
}
else{
l=mid+1;
}
}
cout<<l<<endl;
return 0;
}