Farmer John is an astounding accounting wizard and has realized he might run out of money to run the farm. He has already calculated and recorded the exact amount of money (1 ≤ moneyi ≤ 10,000) that he will need to spend each day over the next N (1 ≤ N ≤ 100,000) days.
FJ wants to create a budget for a sequential set of exactly M (1 ≤ M ≤ N) fiscal periods called "fajomonths". Each of these fajomonths contains a set of 1 or more consecutive days. Every day is contained in exactly one fajomonth.
FJ's goal is to arrange the fajomonths so as to minimize the expenses of the fajomonth with the highest spending and thus determine his monthly spending limit.
Lines 2.. N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day
7 5 100 400 300 100 500 101 400
500
题解:
以所有n天所花钱数为right,其中最大的一天为left,二分。
#include<cstdio>
#include<algorithm>
using namespace std;
#define LL long long
LL a[100005];
LL n,m,left,right,mid,ans;
bool cmp(LL k)
{
LL g,i,j=n;
g=k-a[0];
for(i=1;i<n;i++)
{
g-=a[i];
if(g>=0)
j--;
else
g=k-a[i];
}
if(j<=m)
return true;
else
return false;
}
int main()
{
while(~scanf("%lld %lld",&n,&m))
{
LL i;
left=0;
right=0;
for(i=0;i<n;i++)
{
scanf("%lld",&a[i]);
if(left<a[i])
left=a[i];
right+=a[i];
}
ans=0;
while(left<=right)
{
mid=(left+right)/2;
if(cmp(mid))
{
ans=mid;
right=mid-1;
}
else
left=mid+1;
}
printf("%lld\n",ans);
}
}