Monthly Expense (最大值最小化+二分法)
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
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
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
Hint
If Farmer John schedules the months so that the first two days are a month, the third and fourth are a month, and the last three are their own months, he spends at most $500 in any month. Any other method of scheduling gives a larger minimum monthly limit.繼續二分。最後right即為答案。
本題中的下界為n個數中的最大值,因為這時候,是要劃分為n個區間(即一個數一個區間),left是滿足題意的n個區間和的最大值,
上屆為所有區間的和,因為這時候,是要劃分為1個區間(所有的數都在一個區間裡面), 1<=m<=n, 所以我們所要求的值肯定在 [left, right] 之間。
對於每一個mid,遍歷一遍n個數,看能劃分為幾個區間,如果劃分的區間小於(或等於)給定的m,說明上界取大了, 那麼 另 right=mid,否則另 left=mid+1.
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
int a[100005];
int main()
{
int n,m,sum,maxn,i,j,s,cnt,mid;
while(~scanf("%d%d",&n,&m))
{
sum=0,maxn=0;
for(i=0;i<n;i++) //首先求和和找到最大值。
{
scanf("%d",&a[i]);
sum+=a[i];
maxn=max(maxn,a[i]);
}
while(maxn<sum)
{
mid=(sum+maxn)/2;
s=0,cnt=0;
for(i=0;i<n;i++)
{
s+=a[i];
if(s>mid)
{
s=a[i];
cnt++;
}
}
if(cnt<m)
sum=mid;
else
maxn=mid+1;
}
printf("%d\n",maxn);
}
}