poj 3273 Monthly Expense

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
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.
 
思路:
本题用二分法,详细思路见注释。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 int a[100000+10];
 4 int main()
 5 {
 6     int n,m,group,high=0,mid,low=0,sum,sum_max,t=0;
 7     int i;
 8     scanf("%d %d",&n,&m);
 9  
10     for(i=0; i<n; i++)
11     {
12         scanf("%d",&a[i]);
13         high+=a[i];//所有天数的花费和作为最大值,相当于只分成一个组
14         if(a[i]>low)
15             low=a[i];//花费最多的那一天的值作为最小值,相当于分成n组
16     }
17 
18     while(low<high)//在low==high之前可能有分组情况为m的,但是不能保证值最小
19     {
20         group=1;
21         mid=(low+high)/2;
22         sum=0;
23         sum_max=0;
24         for(i=0; i<n; i++)
25         {
26             sum+=a[i];
27             if(sum>mid)
28             {
29                 sum=a[i];
30                 group++;
31             }
32         }
33         if(group<=m)
34             high=mid;
35         else
36             low=mid+1;
37     }
38     printf("%d\n",low);
39     return 0;
40 }

 

posted @ 2013-08-06 00:55  小の泽  阅读(115)  评论(0)    收藏  举报