POJ3273--Monthly Expense

来源:互联网 发布:尤克里里怎么调音软件 编辑:程序博客网 时间:2024/05/21 19:38

Description

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 nextN (1 ≤ N ≤ 100,000) days.

FJ wants to create a budget for a sequential set of exactly M (1 ≤ MN) 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 andM
Lines 2..N+1: Line i+1 contains the number of dollars Farmer John spends on theith day

Output

Line 1: The smallest possible monthly limit Farmer John can afford to live with.

Sample Input

7 5100400300100500101400

Sample Output

500
/*对于每个mid值,看能包成几包,如果包数比m小,显然我们取大了。因为每个包包的天数都是连续的,所以我们可以针对起点,来二分枚举终点。这样的话就需要一个数组来存前缀和*/#include <iostream>#include <cstdio>using namespace std;int cost[100008];int S[100008];int day,bag;inline int max(int a,int b){return a>b?a:b;}int f(int x){int bb=0,l=1,r=day,wei=0,tou=0;while(wei!=day){bb++;l=tou,r=day;while(l<r){int mid=(l+r)/2;if(S[mid]-S[tou]>x)//无法包在体积为x的包里{r=mid;}else l=mid;if(l+1==r){if(S[r]-S[tou]<=x){l=r;}break;}}tou=l;wei=l;}return bb;}int main(){while(scanf("%d%d",&day,&bag)==2){int minv=0;for(int i=1;i<=day;i++){S[0]=0;scanf("%d",&cost[i]);if(i==1)S[i]=cost[i];else S[i]=S[i-1]+cost[i];minv=max(minv,cost[i]);}int l=minv,r=S[day];//上限就是把全部的钱都包在一个包里。下限如果不弄最大消费那天的话,在最上面那个二分得特殊处理否则死循环while(l<r){int mid=(l+r)/2;if(f(mid)<=bag){r=mid;}else l=mid;if(l+1==r){if(f(l)>bag){l=r;}break;}}printf("%d\n",l);}return 0;}