Monthly Expense -POJ - 3273

         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 ≤ 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 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

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.14:17:46
     典型的二分,注意坑点!!!!
 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 #define MAX 100005
 5 using namespace std;
 6 int N,M;
 7 int v[MAX];
 8 bool test(double V)
 9 {   int ans=0,cnt=0;
10     for(int i=0;i<N;i++){
11         //if(ans+v[i]>V)
12         //{  ans=v[i];
13         //   cnt++;
14         //}
15         //else ans+=v[i];
16         ans+=v[i];
17         if(ans>V){
18             ans=0;
19             cnt++;
20             i--;
21         }
22     }
23     cnt++;              //注意一定要加上最后一次!!!!
24     if(cnt>M) return false;
25     else return true;
26 }
27 int main()
28 {   cin>>N>>M;
29     int num=0,ma=0;
30     for(int i=0;i<N;i++) 
31     {  scanf("%d",&v[i]);
32        num+=v[i];
33        ma=max(ma,v[i]);
34     }
35     double left=ma*(1.0);
36     double right=num*(1.0);
37     double mid;
38     while((right-left)>1e-6){
39          mid=(left+right)/2;
40          if(test(mid)) right=mid;
41          else left=mid;
42     }
43     printf("%d\n",int(mid+0.5));             //一般输出是int型的话,mid要加0.5;或者将right作为答案。!!!
44     //printf("%d\n",int(right));             //如果输出double,则可以直接用mid!!!
45     return 0;
46 }

 

posted @ 2017-03-22 14:19  天之道,利而不害  阅读(273)  评论(0编辑  收藏  举报