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
思路:二分地量就不说了,都懂得,关键在于判定,可以通过你模拟的值(即二分时的量)来进行周期划分,看满足你模拟的值最少周期数是多少,如果大于
m,显然是不满足的,如果小于,那么划分m组是绰绰有余的,等于就不用说了。。重要的是注意确定一个分段点后,起点在哪儿,是最后一个满足的数?还是接下来这个不满足的数?而且要注意比较一天的情况,因为一天也可能是一个周期。代码有详细的标注。
AC代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 using namespace std; 5 6 7 8 9 int main() 10 { 11 int N,M,sum=0,max=0,left,right,mid; 12 13 cin>>N>>M; 14 15 int a[N]; 16 17 for(int i=0;i<N;i++) 18 { 19 cin>>a[i]; 20 sum+=a[i]; 21 if(a[i]>max) 22 max=a[i]; 23 } 24 25 left=max; 26 right=sum; 27 28 int count,sum2; 29 while(left<right) 30 { 31 count=1,sum2=0; 32 mid=(left+right)/2; 33 for(int i=0;i<N;i++) 34 { 35 sum2+=a[i]; 36 if(sum2>mid) 37 { 38 count++; 39 sum2=a[i]; 40 41 } 42 43 } 44 if(count>M) 45 { 46 left=mid+1; 47 } 48 else 49 { 50 right=mid-1; 51 } 52 } 53 54 cout<<right<<endl; 55 56 57 return 0; 58 }