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.
Input
Line 1: Two space-separated integers: N and M
Lines 2.. N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day
Output
Line 1: The smallest possible monthly limit Farmer John can afford to live with.
Sample Input
7 5 100 400 300 100 500 101 400
Sample Output
500
这道题用二分搜索,开始时,上界就是每一天的钱相加之后的和,下界就是每一天花的钱的最大值。
对于每一个mid,遍历一遍n个数,看能划分为几个区间,如果划分的区间小于(或等于)给定的m,说明上界取大了, 那么 另 right=mid,否则另 left=mid+1.
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int money[100005];
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
int r=0,l=-1;
memset(money,0,sizeof(money));
for(int i=0; i<n; i++)
{
scanf("%d",&money[i]);
if(l<money[i])
l=money[i];
r+=money[i];
}
int mid,sum=1,num=0,ans=-1;
while(l<=r)
{
mid=(r+l)/2;
num=0;
sum=1;
for(int i=0; i<n; i++)
{
if(num+money[i]<=mid)
{
num+=money[i];
}
else
{
num=money[i];
sum++;
}
}
if(sum<=m)
{
ans=mid;
r=mid-1;
}
else
l=mid+1;
}
printf("%d\n",ans);
}
l=0,r=inf,ans=-1;
while(l<=r)
{
mid=(l+r)/2;
if(judge(mid))
{
ans=mid;
r=mid-1;
}
else
l=mid+1;
}
print("%d\n",ans);
}