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 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
Lines 2..N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day
Output
Sample Input
7 5
100
400
300
100
500
101
400
Sample Output
500
Hint
#include<stdio.h>
#define MAX 100003
int main()
{
int N,M;
int low,high,mid;
int i,res,mon,sum,days,a[MAX];//res记录合适的周期金钱,mon记录分了多少个周期,sum记录连续几天的金钱和,days记录连续几天是可行的,mon记录间断点。
while(scanf("%d%d",&N,&M)!=EOF)
{
high=0;
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
high+=a[i];
}
low=0;
while(high-low>=0)
{
sum=0;
mon=0;
days=0;
mid=(high+low)/2;
for(i=0;i<N;i++)
{
if(a[i]+sum>mid)
{
sum=0;
if(days>=1)//days是用来分别几天和0天的情况,即是否存在至少一天满足要求。
{
i--;//当出现间断点时,即此时间断点在i和i-1之间,a[i]是不符合要求的,所以下一轮要作为起点,所以i--.
days=0;//且days要清0.
mon++;//间断点加一。
}
else
{
mon=-1;//如果只一天得金钱都不符合,则赋值-1,并跳出。
break;
}
}
else//如果仍满足,sum则累加,连续的天数加一。
{
sum+=a[i];
days++;
}
if(mon==-1)//如果有一天的金钱比mid大,则退出,不需在循环。
break;
}
if(mon==-1)
{
low=mid+1;
continue;
}
if(mon+1>M)//因为mon是间断点,所以是将整个天数分为mon+1块。
low=mid+1;
else
{
high=mid-1;
res=mid;//符合则记录。
}
}
printf("%d\n",res);
}
return 0;
}